Angular ViewChild & ContentChild
Learn Angular ViewChild and ContentChild decorators in detail with architecture diagrams, lifecycle integration, practical examples, ViewChildren, ContentChildren, ViewContainerRef, and interview questions.
Angular provides powerful decorators to access elements, directives, and child components directly from a component class.
The two most commonly used decorators are:
- @ViewChild()
- @ContentChild()
Understanding when to use each decorator is an essential Angular interview topic because it demonstrates knowledge of Component Lifecycle, Content Projection, and DOM Interaction.
Table of Contents
- What are View Queries?
- What is ViewChild?
- What is ContentChild?
- View vs Content
- ViewChildren & ContentChildren
- static: true vs false
- Lifecycle Integration
- ViewContainerRef
- Real-World Examples
- Best Practices
- Top 10 Interview Questions
- Summary
What are View Queries?
View Queries allow Angular components to retrieve references to:
- Child Components
- HTML Elements
- Directives
- Template References
Angular provides two major query types:
| Query | Purpose |
|---|---|
| View Queries | Access component's own view |
| Content Queries | Access projected content |
View vs Content
Understanding the difference is critical.
flowchart TD
ParentComponent
ParentComponent --> ChildComponent
ChildComponent --> Template
ParentComponent --> ProjectedContent
ProjectedContent --> NgContent
NgContent --> ChildComponent
- View → HTML declared inside the component itself.
- Content → HTML projected from the parent using
<ng-content>.
What is @ViewChild()?
@ViewChild() retrieves the first matching element, directive, or child component from the component's own template.
It is commonly used for:
- Accessing child components
- Calling child methods
- Reading DOM elements
- Integrating third-party libraries
ViewChild Architecture
flowchart LR
ParentComponent
ParentComponent --> Template
Template --> ChildComponent
ParentComponent --> ViewChild
ViewChild --> ChildComponent
ViewChild Example (Child Component)
Child Component
@Component({
selector: 'app-child',
standalone: true,
template: `
<h2>Child Component</h2>
`
})
export class ChildComponent {
refresh() {
console.log("Child Refreshed");
}
}
Parent Component
@Component({
selector: 'app-parent',
standalone: true,
imports: [ChildComponent],
template: `
<app-child></app-child>
`
})
export class ParentComponent implements AfterViewInit {
@ViewChild(ChildComponent)
child!: ChildComponent;
ngAfterViewInit() {
this.child.refresh();
}
}
Console
Child Refreshed
Accessing HTML Elements
<input #searchBox>
<button (click)="focus()">
Focus
</button>
@ViewChild("searchBox")
searchBox!: ElementRef<HTMLInputElement>;
focus(){
this.searchBox.nativeElement.focus();
}
ViewChild Lifecycle
flowchart TD
Constructor
Constructor --> OnInit
OnInit --> AfterViewInit
AfterViewInit --> ViewChildAvailable
ViewChildAvailable --> UseReference
Important
@ViewChild() becomes available after ngAfterViewInit() (unless static: true is used).
static: true vs static: false
@ViewChild(ChildComponent,{
static:true
})
child!:ChildComponent;
@ViewChild(ChildComponent,{
static:false
})
child!:ChildComponent;
| Option | Available |
|---|---|
| static: true | Before ngOnInit() |
| static: false (default) | After ngAfterViewInit() |
Use:
- true → Element always exists.
- false → Element created conditionally (
*ngIf,@if).
What is @ContentChild()?
@ContentChild() accesses content projected into a component using <ng-content>.
Unlike ViewChild, it cannot access elements declared inside the component template.
ContentChild Architecture
flowchart TD
Parent
Parent --> HTMLContent
HTMLContent --> NgContent
NgContent --> ChildComponent
ChildComponent --> ContentChild
Content Projection Example
Child Component
<div class="card">
<ng-content></ng-content>
</div>
@Component({
selector:'app-card',
standalone:true,
templateUrl:'card.component.html'
})
export class CardComponent{}
Parent Component
<app-card>
<h2 #title>
Angular Interview
</h2>
</app-card>
Access with ContentChild
@ContentChild("title")
title!:ElementRef;
ngAfterContentInit(){
console.log(
this.title.nativeElement.textContent
);
}
Output
Angular Interview
ContentChild Lifecycle
flowchart TD
Constructor
Constructor --> OnInit
OnInit --> AfterContentInit
AfterContentInit --> ContentChildAvailable
ViewChild vs ContentChild
| Feature | ViewChild | ContentChild |
|---|---|---|
| Access | Component View | Projected Content |
| Template Source | Own HTML | Parent HTML |
| Lifecycle | AfterViewInit | AfterContentInit |
| Uses | Child Components, Elements | ng-content |
| Common Use | DOM access | Content Projection |
ViewChildren
Used when multiple child components exist.
@ViewChildren(UserComponent)
users!:QueryList<UserComponent>;
Example
ngAfterViewInit(){
this.users.forEach(
user=>console.log(user)
);
}
ViewChildren Architecture
flowchart TD
Parent
Parent --> User1
Parent --> User2
Parent --> User3
Parent --> ViewChildren
ContentChildren
Used when multiple projected elements exist.
@ContentChildren("title")
titles!:QueryList<ElementRef>;
Useful when multiple projected items need to be processed.
QueryList
ViewChildren and ContentChildren return a QueryList.
Useful methods:
this.users.first
this.users.last
this.users.forEach()
this.users.toArray()
this.users.length
ViewContainerRef
ViewContainerRef allows dynamic component creation.
constructor(
private viewContainer:
ViewContainerRef
){}
Dynamic Component
this.viewContainer.createComponent(
UserComponent
);
Dynamic Component Architecture
flowchart LR
ButtonClick
ButtonClick --> ViewContainerRef
ViewContainerRef --> CreateComponent
CreateComponent --> Browser
Real-World Banking Example
flowchart TD
Dashboard
Dashboard --> ChartComponent
Dashboard --> TableComponent
Dashboard --> NotificationComponent
Dashboard --> ViewChild
ViewChild --> RefreshCharts
Scenario:
- Dashboard accesses
ChartComponentusingViewChild. - After new transactions arrive, Dashboard invokes
refreshChart()on the child component. - The chart updates without recreating the component.
Common Use Cases
| Requirement | Solution |
|---|---|
| Focus Input | ViewChild |
| Call Child Method | ViewChild |
| Access Canvas | ViewChild |
| Chart.js Initialization | ViewChild |
| Projected HTML | ContentChild |
| Multiple Child Components | ViewChildren |
| Multiple Projected Elements | ContentChildren |
| Dynamic Components | ViewContainerRef |
Best Practices
- Use
ViewChildonly when component interaction cannot be achieved using@Input()and@Output(). - Access
ViewChildreferences inngAfterViewInit(). - Access
ContentChildreferences inngAfterContentInit(). - Prefer
Renderer2over direct DOM manipulation. - Keep components loosely coupled.
- Use
ViewChildrenfor collections instead of multipleViewChilddecorators. - Avoid unnecessary DOM access.
Common Mistakes
- Accessing
ViewChildinside the constructor. - Accessing
ContentChildbeforengAfterContentInit(). - Overusing
ViewChildinstead of component communication. - Direct DOM manipulation with
nativeElement. - Ignoring
QueryListchanges for dynamic views.
Top 10 Angular ViewChild & ContentChild Interview Questions
1. What is @ViewChild()?
Answer
@ViewChild() retrieves the first matching child component, directive, or DOM element from the component's own view.
2. What is @ContentChild()?
Answer
@ContentChild() retrieves the first matching element or directive from content projected into a component using <ng-content>.
3. What is the difference between View and Content?
| View | Content |
|---|---|
| Component's own template | Projected from parent |
| Accessed with ViewChild | Accessed with ContentChild |
4. When is ViewChild available?
Answer
By default, it is available after ngAfterViewInit().
If static: true is specified and the queried element always exists, it can be accessed before ngOnInit().
5. When is ContentChild available?
Answer
It becomes available after ngAfterContentInit() because Angular must first project the parent's content into the child component.
6. What is ViewChildren?
Answer
@ViewChildren() retrieves multiple matching child components or elements and returns them as a QueryList.
7. What is ContentChildren?
Answer
@ContentChildren() retrieves multiple projected content elements or directives and returns them as a QueryList.
8. What is QueryList?
Answer
QueryList is an Angular collection that provides helper methods such as first, last, forEach(), map(), length, and toArray() for working with multiple queried items.
9. What is ViewContainerRef?
Answer
ViewContainerRef is an Angular API used to dynamically create, insert, and remove components at runtime.
10. When should you use ViewChild instead of @Input()?
Answer
Use ViewChild when the parent needs direct access to a child component's methods or DOM elements. For simple data passing, @Input() is preferred because it keeps components loosely coupled.
Interview Cheat Sheet
| Topic | Remember |
|---|---|
| ViewChild | Access own template |
| ContentChild | Access projected content |
| ViewChildren | Multiple child components |
| ContentChildren | Multiple projected elements |
| View Lifecycle | ngAfterViewInit() |
| Content Lifecycle | ngAfterContentInit() |
| Collection Type | QueryList |
| Dynamic Components | ViewContainerRef |
| DOM Access | ElementRef |
| Preferred Communication | @Input() / @Output() |
Summary
@ViewChild() and @ContentChild() are powerful Angular decorators that provide direct access to child components, DOM elements, and projected content. ViewChild is ideal for interacting with a component's own view, while ContentChild is designed for content projection scenarios. Together with ViewChildren, ContentChildren, and ViewContainerRef, they enable advanced UI interactions, dynamic component creation, and flexible component composition. Using these APIs correctly helps build clean, maintainable, and high-performance Angular applications.
Next Article
➡️ 16-Angular-Directives-QA.md