Skip to main content

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

  1. What it does:
  • Lets you work with content inserted from the parent component.
  • You can access the projected elements through @ContentChild or @ContentChildren.
  1. When it is called:
  • Once, after the content is first projected into the component.
  • Before any view checks (AfterViewInit) and after ngOnInit().

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 ready
Premium

A concise answer to help you respond confidently on this topic during an interview.