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
Component (TS)
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:
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
HTML
Now Angular knows each user by its id.
⭐ Using Index Instead of ID
If items do not have IDs, you can use index:
TS:
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:
Compare identity (ID) of each old and new item
Keep DOM element if ID is the same
Move DOM element if order changed
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.
