Performance: Structural vs attribute directives
This concept affects how Angular manipulates the DOM structure and attributes, impacting rendering speed and layout stability.
<div [ngStyle]="{'visibility': isVisible ? 'visible' : 'hidden'}">Content</div><div *ngIf="isVisible">Content</div>| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Structural directive (*ngIf) | Adds/removes nodes | Triggers 1 reflow per toggle | Medium paint cost | [X] Bad for frequent toggles |
| Attribute directive ([ngStyle]) | No DOM changes | No reflows | Low paint cost | [OK] Good for toggling visibility |
<div *ngFor="let item of items">{{item}}</div> uses *ngFor="let item of items" which is correct.<div *ngFor="let item of items">{{item}}</div> [OK]<ul> <li *ngIf="showItem">Item 1</li> <li>Item 2</li> </ul>
showItem is false.<button *ngIf="isEnabled" [disabled]="isDisabled">Click Me</button>
isEnabled and isDisabled are boolean variables.Pass the test and this pattern moves unknown