What is @ViewChild and @ContentChild in Angular?

Why Interviewers Ask This

Interviewers use this question to quickly assess whether a candidate has the foundational knowledge required for Angular development. It reveals whether you understand the building blocks that more complex concepts rely on.

Answer

@ViewChild gives a component access to a child component, directive, or DOM element in its own template (view). @ContentChild accesses content projected into the component via <ng-content>. @ViewChild usage: @ViewChild("myInput") myInputRef!: ElementRef; @ViewChild(ChildComponent) childComp!: ChildComponent; @ViewChild(NgForm) form!: NgForm;. The argument can be: a template reference variable name (string), a component/directive type, or a provider token. Static option: @ViewChild("ref", { static: true }) — resolves before change detection (accessible in ngOnInit); static: false (default) — resolves after change detection (accessible in ngAfterViewInit). Access timing: for static: false, the ViewChild is available in ngAfterViewInit(), NOT in ngOnInit. Accessing before this returns undefined. @ViewChildren: access a QueryList of ALL matching elements: @ViewChildren(ChildComponent) children!: QueryList<ChildComponent>;. @ContentChild: @ContentChild(AlertComponent) alert!: AlertComponent; — access a component projected via <ng-content>. Available in ngAfterContentInit(). @ContentChildren: QueryList of all projected matching elements. Direct DOM manipulation via ElementRef: avoid using this.myInputRef.nativeElement.focus() directly when possible — use Renderer2 for cross-platform compatibility (Angular Universal/SSR). Use Angular reactive approaches over DOM manipulation when possible.

Pro Tip

Back up your answer with a specific project or situation. Saying 'In my last Angular project, I used this when...' immediately makes your answer more credible and memorable.