Performance: TrackBy in ngFor
This affects how Angular updates the DOM when rendering lists, improving rendering speed and reducing layout shifts.
Jump into concepts and practice - no test required
<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 |
trackBy in an ngFor directive in Angular?ngFor doesngFor repeats a template for each item in a list, rendering them in the view.trackBytrackBy helps Angular know which items changed by uniquely identifying them, so it only updates those items instead of re-rendering the whole list.trackBy in an ngFor loop?ngFor syntax with trackBytrackBy followed by the function name without parentheses.*ngFor="let item of items; trackBy: trackByFn" matches the correct syntax: *ngFor="let item of items; trackBy: trackByFn". Others either miss the keyword or use parentheses incorrectly.items array is updated by adding a new item?items = [{id: 1, name: 'A'}, {id: 2, name: 'B'}];
trackByFn(index: number, item: any) {
return item.id;
}<div *ngFor="let item of items; trackBy: trackByFn">{{item.name}}</div>trackByFn returns the unique id of each item, so Angular can track items by their IDs.trackByFn to detect only the new item and renders just that one, not the entire list.trackBy function used in an ngFor loop:trackByFn(index: number, item: any) {
return index + 1;
}index + 1, which changes if the list order changes or items are added/removed.trackBy. Which trackBy function below correctly handles this scenario to avoid unnecessary re-renders when the list updates?user.name is not reliable. The unique user.id is the best choice.user.name (not unique), B uses user.id (stable and unique), C uses index (unstable), D returns the whole user object (not recommended).