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 |
Angular viewChild vs ContentChild – Interview Questions
Q 1: What is viewChild?
Ans: Accesses elements inside component template.
Q 2: What is ContentChild?
Ans: Accesses projected content inside ng-content.
Q 3: When is ContentChild used?
Ans: When working with content projection.
Q 4: Does viewChild access projected content?
Ans: No.
Q 5: Which lifecycle hook works with ContentChild?
Ans: ngAfterContentInit.
Angular viewChild vs ContentChild – Objective Questions (MCQs)
Q1. @ViewChild is used to access:
Q2. @ContentChild is used to access:
Q3. @ViewChild works with:
Q4. @ContentChild works after:
Q5. Which decorator accesses projected content?