0
0
Angularframework~8 mins

Directive execution and DOM manipulation in Angular - Performance & Optimization

Choose your learning style9 modes available
Performance: Directive execution and DOM manipulation
HIGH IMPACT
This affects how fast the page renders and responds by controlling when and how DOM elements are created or changed.
Manipulating DOM elements inside Angular directives
Angular
import { Directive, ElementRef, Renderer2, AfterViewInit } from '@angular/core';

@Directive({ selector: '[goodDomManip]' })
export class GoodDomManipDirective implements AfterViewInit {
  constructor(private el: ElementRef, private renderer: Renderer2) {}

  ngAfterViewInit() {
    const fragment = document.createDocumentFragment();
    for (let i = 0; i < 1000; i++) {
      const div = this.renderer.createElement('div');
      this.renderer.setProperty(div, 'textContent', `Item ${i}`);
      fragment.appendChild(div);
    }
    this.el.nativeElement.appendChild(fragment);
  }
}
Using a document fragment batches DOM insertions, causing only one reflow and letting Angular run this after initial rendering.
📈 Performance GainSingle reflow triggered, reduces blocking time by 90% or more.
Manipulating DOM elements inside Angular directives
Angular
import { Directive, ElementRef } from '@angular/core';

@Directive({ selector: '[badDomManip]' })
export class BadDomManipDirective {
  constructor(private el: ElementRef) {
    for (let i = 0; i < 1000; i++) {
      const div = document.createElement('div');
      div.textContent = `Item ${i}`;
      this.el.nativeElement.appendChild(div);
    }
  }
}
This creates and appends 1000 DOM nodes synchronously during directive construction, blocking rendering and causing many reflows.
📉 Performance CostTriggers 1000 reflows and blocks rendering for 100+ ms on typical devices.
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Direct DOM append in constructor1000 nodes appended individually1000 reflowsHigh paint cost[X] Bad
Batch DOM append with DocumentFragment in ngAfterViewInit1000 nodes appended once1 reflowLow paint cost[OK] Good
Rendering Pipeline
Directive code runs during Angular's rendering cycle. Direct DOM changes cause style recalculations and layout reflows. Batching DOM updates reduces layout thrashing and paint cost.
Style Calculation
Layout
Paint
Composite
⚠️ BottleneckLayout (reflow) stage is most expensive due to repeated DOM insertions.
Core Web Vital Affected
LCP, INP
This affects how fast the page renders and responds by controlling when and how DOM elements are created or changed.
Optimization Tips
1Avoid direct DOM manipulation in directive constructors to prevent blocking rendering.
2Use ngAfterViewInit lifecycle hook for heavy DOM updates to defer work until after initial paint.
3Batch DOM changes with DocumentFragment or Renderer2 to minimize reflows and paints.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance problem with manipulating DOM directly inside an Angular directive constructor?
AIt increases CSS selector complexity.
BIt blocks rendering by causing many reflows synchronously.
CIt delays network requests.
DIt reduces JavaScript bundle size.
DevTools: Performance
How to check: Record a performance profile while loading the page with the directive. Look for long scripting tasks and multiple layout events.
What to look for: Multiple layout (reflow) events and long scripting blocks indicate poor DOM manipulation. A single layout event with shorter scripting time indicates good performance.