Directives, Pipes & Templates
Angular ViewChild and ContentChild
@ViewChild queries an element or component from the component’s own template. @ContentChild queries content that was projected into it. Both give you a typed handle for imperative work such as focusing or measuring.
What is ViewChild and ContentChild in Angular?
@ViewChild queries an element or component from the component’s own template. @ContentChild queries content that was projected into it. Both give you a typed handle for imperative work such as focusing or measuring.
ViewChild and ContentChild example
import { AfterViewInit, Component, ElementRef, ViewChild } from '@angular/core';
@Component({
selector: 'app-search',
standalone: true,
template: `<input #box placeholder="Search jobs">`,
})
export class SearchComponent implements AfterViewInit {
@ViewChild('box') box!: ElementRef<HTMLInputElement>;
ngAfterViewInit(): void {
this.box.nativeElement.focus(); // available only after the view is initialised
}
}Key points to remember
- View queries resolve in ngAfterViewInit; content queries in ngAfterContentInit.
- Pass { static: true } to read a query in ngOnInit when the element is not inside a structural directive.
- The signal-based viewChild() function is the modern alternative in recent Angular versions.
Common mistakes with ViewChild and ContentChild
- Reading a ViewChild in ngOnInit and getting undefined.
- Querying an element inside *ngIf without handling the case where it does not exist yet.
Angular ViewChild and ContentChild— Interview Questions & FAQs
Why is my ViewChild undefined?+
You read it too early. View queries are resolved after the template renders, so read them in ngAfterViewInit — or pass { static: true } if the element is not wrapped in a structural directive.
