Blog>
Snippets

Using TrackBy with ngFor for Optimized Rendering

Show how to use the trackBy function to optimize ngFor performance when dealing with a list of items with unique identifiers.
// In your Angular component class
trackByItemId(index, item) {
  return item.id; // Unique identifier for each item
}
This is the trackBy function that takes an index and an item, and returns the unique identifier (id in this case) of each item. It's used by ngFor to track items and optimize DOM updates.
<!-- In your Angular template -->
<ul>
  <li *ngFor="let item of items; trackBy: trackByItemId">
    {{ item.name }}
  </li>
</ul>
This is how you use the trackBy function in the Angular template. It's included in the ngFor directive with the syntax trackBy: function. This optimizes rendering by preventing the recreation of DOM elements for items that have not changed.