Performance: Custom structural directives
MEDIUM IMPACT
Custom structural directives affect how Angular manipulates the DOM structure, impacting rendering speed and layout stability.
import { Directive, TemplateRef, ViewContainerRef } from '@angular/core'; @Directive({ selector: '[appGoodIf]' }) export class GoodIfDirective { private hasView = false; constructor(private templateRef: TemplateRef<any>, private viewContainer: ViewContainerRef) {} set appGoodIf(condition: boolean) { if (condition && !this.hasView) { this.viewContainer.createEmbeddedView(this.templateRef); this.hasView = true; } else if (!condition && this.hasView) { this.viewContainer.clear(); this.hasView = false; } } }
import { Directive, TemplateRef, ViewContainerRef } from '@angular/core'; @Directive({ selector: '[appBadIf]' }) export class BadIfDirective { constructor(private templateRef: TemplateRef<any>, private viewContainer: ViewContainerRef) {} set appBadIf(condition: boolean) { this.viewContainer.clear(); if (condition) { this.viewContainer.createEmbeddedView(this.templateRef); } } }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Clearing and recreating views on every condition change | Multiple clears and creates | Triggers 1 reflow per change | High paint cost due to layout shifts | [X] Bad |
| Tracking view state and updating only on change | Minimal DOM operations | Reflows only on actual DOM changes | Lower paint cost with stable layout | [OK] Good |