Performance: ngAfterViewInit for view ready
This lifecycle hook affects when DOM-dependent code runs, impacting interaction readiness and rendering stability.
ngAfterViewInit() {
const element = document.querySelector('.my-element');
element.style.width = '100px';
}ngOnInit() {
const element = document.querySelector('.my-element');
element.style.width = '100px';
}| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| DOM manipulation in ngOnInit | Early DOM access, may fail or cause forced reflows | Multiple reflows if elements not ready | Higher paint cost due to layout thrashing | [X] Bad |
| DOM manipulation in ngAfterViewInit | DOM fully ready, safe to access | Single reflow triggered | Lower paint cost, smoother rendering | [OK] Good |
ngAfterViewInit lifecycle hook in Angular?ngAfterViewInit runsngAfterViewInit runs after Angular fully initializes the component's view and its child views, making it safe to access view elements.ngAfterViewInit in an Angular component?import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core';
@Component({ selector: 'app-sample', template: `Content` })
export class SampleComponent implements AfterViewInit {
@ViewChild('box') box!: ElementRef;
ngAfterViewInit() {
console.log(this.box.nativeElement.textContent);
}
}this.box.nativeElement.textContent, which is the text inside the <div> with #box, which is "Content".import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core';
@Component({ selector: 'app-test', template: `Paragraph
` })
export class TestComponent implements AfterViewInit {
@ViewChild('para') para!: ElementRef;
ngOnInit() {
console.log(this.para.nativeElement.textContent);
}
ngAfterViewInit() {
console.log('View initialized');
}
}this.para.nativeElement.textContent inside ngOnInit, which runs before the view is ready, causing undefined or error.ngAfterViewInit to do this in the parent component?
Child component template: <div #childBox>Child Content</div> Parent component code options:
ngAfterViewInit, after the parent's view and child views are fully initialized.Pass the test and this pattern moves unknown