What does ngAfterContentInit() do? When is it called?
In Angular, ngAfterContentInit() is a lifecycle hook that is called once, after Angular has inserted (projected) external content into the component through <ng-content>.
Key points
- What it does:
- Lets you work with content inserted from the parent component.
- You can access the projected elements through
@ContentChildor@ContentChildren.
- When it is called:
- Once, after the content is first projected into the component.
- Before any view checks (
AfterViewInit) and afterngOnInit().
Example:
ts
export class ChildComponent implements AfterContentInit {
@ContentChild('projectedContent') content: ElementRef;
ngAfterContentInit() {
console.log('Projected content is available:', this.content.nativeElement);
}
}html
<child-component>
<p #projectedContent>Hello from the parent component!</p>
</child-component>- In
ngAfterContentInit, it is already safe to work with the<p>inserted by the parent.
In other words, ngAfterContentInit is a hook for working with content projected into the component, after it has been inserted into the DOM.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.