How to Use trackBy in ngFor for Better Angular Performance
Use
trackBy in Angular's ngFor to tell Angular how to identify items in a list uniquely. This helps Angular reuse existing DOM elements instead of recreating them, improving performance especially for large or dynamic lists.Syntax
The trackBy function is used inside the ngFor directive like this:
*ngFor="let item of items; trackBy: trackByFn"— tells Angular to usetrackByFnto track items.trackByFn(index: number, item: any): any— a function that returns a unique identifier for each item.
This function helps Angular detect which items changed, added, or removed.
typescript
<div *ngFor="let item of items; trackBy: trackByFn">{{ item.name }}</div> trackByFn(index: number, item: any): any { return item.id; // unique id for each item }
Example
This example shows a list of users rendered with ngFor using trackBy. When the list updates, Angular reuses DOM elements for users with the same id, improving performance.
typescript
import { Component } from '@angular/core'; @Component({ selector: 'app-user-list', template: ` <button (click)="shuffleUsers()">Shuffle Users</button> <ul> <li *ngFor="let user of users; trackBy: trackByUserId"> {{ user.id }} - {{ user.name }} </li> </ul> ` }) export class UserListComponent { users = [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }, { id: 3, name: 'Carol' } ]; trackByUserId(index: number, user: any): number { return user.id; } shuffleUsers() { this.users = this.users .map(value => ({ value, sort: Math.random() })) .sort((a, b) => a.sort - b.sort) .map(({ value }) => value); } }
Output
<button>Shuffle Users</button>
- 1 - Alice
- 2 - Bob
- 3 - Carol
Common Pitfalls
Common mistakes when using trackBy include:
- Not returning a unique identifier, causing Angular to recreate all DOM elements.
- Returning the index instead of a unique id, which breaks when the list order changes.
- Not using
trackByat all for large or frequently changing lists, leading to poor performance.
Always ensure your trackBy function returns a stable and unique value for each item.
typescript
/* Wrong: returns index, breaks on reorder */ trackByIndex(index: number, item: any): number { return index; } /* Right: returns unique id */ trackById(index: number, item: any): any { return item.id; }
Quick Reference
- Purpose: Optimize
ngForby tracking items uniquely. - Usage: Add
trackBy: yourFunctioninside*ngFor. - Function: Takes
indexanditem, returns unique id. - Benefit: Prevents unnecessary DOM updates, improves performance.
Key Takeaways
Use trackBy in ngFor to uniquely identify list items and improve rendering performance.
The trackBy function must return a stable, unique identifier for each item, like an id.
Avoid using the index as the trackBy value when list order can change.
Without trackBy, Angular recreates DOM elements unnecessarily on list changes.
Implement trackBy especially for large or frequently updated lists to optimize UI updates.