ngAfterContentInit called in Angular?<ng-content>. When does Angular call the ngAfterContentInit lifecycle hook?The ngAfterContentInit hook runs once after Angular projects external content into the component and initializes it. This means it waits for both the component's own view and any projected content to be ready.
ngAfterContentInit?ngAfterContentInit?import { Component, ContentChild, AfterContentInit, ElementRef } from '@angular/core'; @Component({ selector: 'child-comp', template: `<ng-content></ng-content>` }) export class ChildComp implements AfterContentInit { @ContentChild('projected') projectedContent!: ElementRef; ngAfterContentInit() { console.log(this.projectedContent.nativeElement.textContent.trim()); } } // Usage in parent template: // <child-comp><p #projected>Hello Angular</p></child-comp>
@ContentChild decorator finds the element inside projected content after content init.The @ContentChild decorator references the element with template reference #projected inside the projected content. By ngAfterContentInit, this element is available, so logging its text content outputs "Hello Angular".
ngAfterContentInit implementationngAfterContentInit method implementations correctly logs the number of projected items using @ContentChildren?import { Component, ContentChildren, QueryList, AfterContentInit, ElementRef } from '@angular/core'; @Component({ selector: 'list-comp', template: `<ng-content></ng-content>` }) export class ListComp implements AfterContentInit { @ContentChildren('item') items!: QueryList<ElementRef>; ngAfterContentInit() { // ??? } }
QueryList has a length property directly to get the number of items.QueryList has a length property that returns the current number of matched items. Use console.log(this.items.length) inside ngAfterContentInit.
@ContentChild return undefined in ngAfterContentInit?@ContentChild('proj') to get a projected element but finds it undefined inside ngAfterContentInit. What is the most likely cause?import { Component, ContentChild, AfterContentInit, ElementRef } from '@angular/core'; @Component({ selector: 'proj-comp', template: `<ng-content></ng-content>` }) export class ProjComp implements AfterContentInit { @ContentChild('proj') projElement!: ElementRef; ngAfterContentInit() { console.log(this.projElement); } } // Usage: // <proj-comp><div>Content without #proj</div></proj-comp>
@ContentChild('proj') looks for an element with #proj inside the projected content. If the projected element lacks this reference, the property will be undefined.
ngAfterContentInit hooks in nested components with projection?ngAfterContentInit hooks in this nested projection scenario?Angular calls ngAfterContentInit on each component after its own projected content is initialized. This happens top-down: the parent component's hook runs after its content is ready, then the child component's hook runs after its own projected content is ready, and so on.