Performance: TrackBy in ngFor
HIGH IMPACT
This affects how Angular updates the DOM when rendering lists, improving rendering speed and reducing layout shifts.
<div *ngFor="let item of items; trackBy: trackById">{{item.name}}</div> trackById(index: number, item: any) { return item.id; }
<div *ngFor="let item of items">{{item.name}}</div>| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| ngFor without trackBy | Removes and recreates all nodes on update | N reflows per update (N = list length) | High paint cost due to full node replacement | [X] Bad |
| ngFor with trackBy | Reuses existing nodes, updates only changed items | Reflows only for changed items | Lower paint cost due to minimal DOM changes | [OK] Good |