Angular provides multiple decorators to access child components, directives, and DOM elements.
Two commonly used are:
- ViewChild
- ContentChild
What is ViewChild in Angular?
ViewChild is used to access:
- A DOM element inside the component’s template
- A child component inside the template
- A directive placed inside the template
- A template reference variable
Note: ViewChild works inside the component’s own HTML template.
Example: Access DOM Element with ViewChild
<!-- parent.component.html -->
<div #titleRef>Welcome to Angular</div>
<button (click)="changeTitle()">Change Title</button>
parent.component.ts
// parent.component.ts
@ViewChild('titleRef') title!: ElementRef;
changeTitle() {
this.title.nativeElement.innerText = "Welcome To TechFliez!";
}
Access Child Component with ViewChild
@ViewChild(ChildComponent) child!: ChildComponent;
ngAfterViewInit() {
this.child.printMessage();
}
What is ContentChild in Angular?
It is used to access
- Projected content passed from parent component
- ng-content inserted elements
- Template reference variables inside ng-content
Example: Using ContentChild to Access Projected Content
parent component template
<app-car>
<h2 #header>Title From Parent</h2>
</app-car>
child component template
<div class="car">
<ng-content></ng-content>
</div>
child component (ts file)
@ContentChild('header') headerRef!: ElementRef;
ngAfterContentInit() {
console.log(this.headerRef.nativeElement.innerText);
}
Note: This will read the text “Title From Parent”.
ViewChild vs ContentChild – Key Differences
| Feature | ViewChild | ContentChild |
|---|---|---|
| Works on | Elements/directives inside component template | Elements/directives projected via ng-content |
| Access Location | View (component HTML) | Content projected by parent |
| Lifecycle Hook | ngAfterViewInit() | ngAfterContentInit() |
| Use Case | Access DOM, directives, child components | Access projected content inside ng-content |
| Updates? | Updates when view changes | Updates when projected content changes |