Performance: ngAfterContentInit for projected content
This lifecycle hook affects the timing of when projected content is initialized and rendered, impacting initial rendering speed and interaction readiness.
ngAfterContentInit() {
// Minimal logic here
this.scheduleHeavyWorkOutsideAngular();
}
scheduleHeavyWorkOutsideAngular() {
setTimeout(() => {
// heavy work deferred after initial render
});
}ngAfterContentInit() {
this.projectedContent.forEach(item => {
// heavy DOM manipulation or complex logic
});
}| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Heavy synchronous logic in ngAfterContentInit | Multiple DOM reads/writes | Triggers multiple reflows | High paint cost due to blocking | [X] Bad |
| Minimal logic with deferred heavy work | Minimal DOM operations initially | Single reflow after paint | Low paint cost, smoother rendering | [OK] Good |
ngAfterContentInit lifecycle hook in Angular?ngAfterContentInit<ng-content> slot.ngAfterContentInit in an Angular component?import { Component, AfterContentInit, ContentChild, ElementRef } from '@angular/core';
@Component({
selector: 'child-comp',
template: ``
})
export class ChildComp implements AfterContentInit {
@ContentChild('projected') projectedContent!: ElementRef;
ngAfterContentInit() {
console.log(this.projectedContent.nativeElement.textContent.trim());
}
}
// Usage in parent template:
// Hello World
@ContentChild('projected') decorator gets the element with template reference #projected projected inside <ng-content>. This is available after content initialization.import { Component, AfterContentInit, ContentChild, ElementRef } from '@angular/core';
@Component({
selector: 'proj-comp',
template: ``
})
export class ProjComp implements AfterContentInit {
@ContentChild('contentRef') content!: ElementRef;
ngAfterContentInit() {
console.log(this.content.nativeElement.textContent);
}
}<proj-comp><p>Test</p></proj-comp>, what error will occur and why?@ContentChild('contentRef') looks for an element with template reference variable #contentRef inside projected content.<p>Test</p> has no #contentRef variable, so content is undefined.this.content.nativeElement causes a runtime error because content is undefined.ngAfterContentInit to achieve this?import { Component, AfterContentInit, ContentChildren, QueryList, ElementRef } from '@angular/core';
@Component({
selector: 'highlight-list',
template: ``
})
export class HighlightList implements AfterContentInit {
@ContentChildren('item') items!: QueryList<ElementRef>;
ngAfterContentInit() {
// What should go here?
}
}ngAfterContentInit implementation:@ContentChildren('item') collects all projected elements with template ref #item into a QueryList. Access the first element with items.first.items.first.nativeElement.style.backgroundColor to highlight the first item safely after content is initialized.Pass the test and this pattern moves unknown