trackBy in Angular

What Is trackBy in Angular?

When Angular uses *ngFor to loop over a list, it re-renders the entire list whenever the array changes—even if only one item changed.

This can cause:

❌ Unnecessary DOM operations
❌ Bad performance (especially with large lists)
❌ Loss of component state inside list items

trackBy helps Angular identify each item uniquely, so only changed items are updated.


🎯 Why Use trackBy?

Use trackBy to:

✔ Improve performance
✔ Prevent re-rendering of unchanged items
✔ Keep state of list items (like input values, selection, animation states)


⭐ Basic Usage of trackBy

Template

<div *ngFor="let user of users; trackBy: trackById">
{{ user.name }}
</div>

Component (TS)

trackById(index: number, item: any) {
return item.id; // unique identifier
}

Here:

  • Angular will track each user by id

  • If the array updates, Angular only re-renders items whose id changed


🧩 Example Without trackBy (Bad Performance)

If your list updates like this:

this.users = [...this.users];

Angular thinks:

“Everything is new!” → Rebuild whole DOM


🧩 Example With trackBy (Optimized)

Angular compares:

Old ID vs New ID
If same ID → Keep existing DOM element
If ID changed → Re-render only that item


⭐ Example: Real Code

TS

users = [
{ id: 1, name: "Sanjit" },
{ id: 2, name: "Aman" },
{ id: 3, name: "Riya" }
];

trackByUserId(index: number, user: any) {
return user.id;
}

HTML

<div *ngFor="let user of users; trackBy: trackByUserId">
{{ user.name }}
</div>

Now Angular knows each user by its id.


⭐ Using Index Instead of ID

If items do not have IDs, you can use index:

<div *ngFor="let item of items; trackBy: trackByIndex">
{{ item }}
</div>

TS:

trackByIndex(i: number) {
return i;
}

Not recommended for dynamically updated lists, but OK for static ones.


⭐ Example: When TrackBy Saves Component State

Without trackBy

If you type inside inputs inside *ngFor, and the list refreshes, Angular recreates all inputs → typing resets.

With trackBy

Angular keeps existing DOM nodes → input values stay.


⭐ The Best Practice

Always use trackBy when:

✔ Items have a unique ID
✔ Working with large lists
✔ Using async data (async | pipe)
✔ Lists update frequently (real-time apps)


🔍 How Angular Internally Uses trackBy

Angular does:

  1. Compare identity (ID) of each old and new item

  2. Keep DOM element if ID is the same

  3. Move DOM element if order changed

  4. Create/remove only necessary items


🎉 One-Line Summary

👉 trackBy makes *ngFor faster by telling Angular how to uniquely identify each item, preventing unnecessary DOM re-rendering.

You may also like...