ngAfterContentInit helps you know when the content you put inside a component from outside is ready. This is useful to work with that content safely.
ngAfterContentInit for projected content in Angular
import { AfterContentInit } from '@angular/core'; export class YourComponent implements AfterContentInit { ngAfterContentInit() { // code to run after projected content is initialized } }
ngAfterContentInit is a lifecycle hook method Angular calls once after the projected content is initialized.
To use it, your component class must implement the AfterContentInit interface.
ChildComponent is ready.import { AfterContentInit, Component } from '@angular/core'; @Component({ selector: 'child-comp', template: `<ng-content></ng-content>` }) export class ChildComponent implements AfterContentInit { ngAfterContentInit() { console.log('Projected content is ready'); } }
#projected and logs its text after content init.import { AfterContentInit, Component, ContentChild, ElementRef } from '@angular/core'; @Component({ selector: 'child-comp', template: `<ng-content></ng-content>` }) export class ChildComponent implements AfterContentInit { @ContentChild('projected') projectedElement!: ElementRef; ngAfterContentInit() { console.log('Projected element text:', this.projectedElement.nativeElement.textContent); } }
This example shows a parent component projecting a paragraph into ChildComponent. The child uses ngAfterContentInit to log when the content is ready and prints the paragraph text.
import { Component, AfterContentInit, ContentChild, ElementRef } from '@angular/core'; @Component({ selector: 'child-comp', template: `<div><ng-content></ng-content></div>` }) export class ChildComponent implements AfterContentInit { @ContentChild('info') infoElement!: ElementRef; ngAfterContentInit() { console.log('Content inside child component is ready.'); console.log('Projected content text:', this.infoElement.nativeElement.textContent.trim()); } } @Component({ selector: 'app-root', template: `<child-comp><p #info>Hello from projected content!</p></child-comp>` }) export class AppComponent {}
ngAfterContentInit runs only once after the first content projection is done.
If the projected content changes later, use ngAfterContentChecked to detect updates.
Always check if @ContentChild or @ContentChildren are defined before using them to avoid errors.
ngAfterContentInit tells you when projected content is ready inside your component.
Use it to safely access or manipulate content passed from outside.
It runs once after Angular inserts the external content into your component.