68. ViewChild and ContentChild
When a component needs programmatic access to elements or components rendered within its own view (local DOM) or projected content (ng-content), we use @ViewChild and @ContentChild.
1. @ViewChild (Accessing Local View)
@ViewChild is used by a component to grab a reference to a DOM element or component/directive that is rendered in its own template.
Use Case: Setting focus on an input, accessing a method on a child component within the current template.
typescript // parent.component.ts import { ViewChild, ElementRef, AfterViewInit } from '@angular/core';
export class ParentComponent implements AfterViewInit {
// 1. Select the DOM element marked with #nameInput @ViewChild('nameInput') nameInputRef: ElementRef | undefined;
// 2. We can only access the view elements after ngAfterViewInit runs ngAfterViewInit(): void { if (this.nameInputRef) { // Access the native DOM element and call focus() this.nameInputRef.nativeElement.focus(); } } }
html
<input type="text" #nameInput>
2. @ContentChild (Accessing Projected Content)
@ContentChild is used to grab a reference to an element or component that was passed into the component via content projection (<ng-content>).
Use Case: A container component needs to know if a specific projected element (like a required header) is present.
typescript
// container.component.ts (The component that has
export class ContainerComponent implements AfterContentInit {
// Look for the element with the .header-title CSS class in the projected content @ContentChild('.header-title') headerRef: ElementRef | undefined;
ngAfterContentInit(): void { console.log('Projected header found?', !!this.headerRef); } }
Key difference in timing: @ContentChild is available in ngAfterContentInit. @ViewChild is available in ngAfterViewInit.