0
0
Angularframework~8 mins

ngAfterViewInit for view ready in Angular - Performance & Optimization

Choose your learning style9 modes available
Performance: ngAfterViewInit for view ready
MEDIUM IMPACT
This lifecycle hook affects when DOM-dependent code runs, impacting interaction readiness and rendering stability.
Running DOM-dependent code after the view is initialized
Angular
ngAfterViewInit() {
  const element = document.querySelector('.my-element');
  element.style.width = '100px';
}
Runs DOM-dependent code only after the view is fully initialized, reducing layout thrashing and improving responsiveness.
📈 Performance GainSingle reflow triggered, improving interaction to next paint (INP) metric.
Running DOM-dependent code after the view is initialized
Angular
ngOnInit() {
  const element = document.querySelector('.my-element');
  element.style.width = '100px';
}
Accessing or manipulating DOM elements before the view is fully initialized can cause errors or force multiple reflows.
📉 Performance CostTriggers multiple reflows if elements are not ready, blocking rendering for tens of milliseconds.
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
DOM manipulation in ngOnInitEarly DOM access, may fail or cause forced reflowsMultiple reflows if elements not readyHigher paint cost due to layout thrashing[X] Bad
DOM manipulation in ngAfterViewInitDOM fully ready, safe to accessSingle reflow triggeredLower paint cost, smoother rendering[OK] Good
Rendering Pipeline
ngAfterViewInit runs after Angular completes rendering the component's view, allowing safe DOM access and manipulation without causing layout thrashing.
Layout
Paint
Composite
⚠️ BottleneckLayout stage is most expensive if DOM is manipulated too early causing multiple reflows.
Core Web Vital Affected
INP
This lifecycle hook affects when DOM-dependent code runs, impacting interaction readiness and rendering stability.
Optimization Tips
1Run DOM-dependent code in ngAfterViewInit, not ngOnInit.
2Avoid accessing DOM before the view is fully initialized to prevent layout thrashing.
3Batch DOM changes after view init to minimize reflows and improve input responsiveness.
Performance Quiz - 3 Questions
Test your performance knowledge
Why is ngAfterViewInit preferred over ngOnInit for DOM manipulation?
ABecause the view is fully initialized and DOM elements are ready
BBecause ngOnInit runs after the view is rendered
CBecause ngAfterViewInit runs before the component is created
DBecause ngOnInit delays rendering
DevTools: Performance
How to check: Record a performance profile while interacting with the component. Look for layout thrashing or multiple forced reflows around component initialization.
What to look for: Check for fewer layout recalculations and faster interaction to next paint (INP) when using ngAfterViewInit.