Blog>
Snippets

TrackBy with ngFor Directive

Use trackBy function with ngFor to prevent DOM re-rendering of identical items. This function returns a unique identifier for each item.
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <ul>
      <li *ngFor="let item of items; trackBy: trackById">
        {{item.id}}: {{item.name}}
      </li>
    </ul>
  `
})
export class AppComponent {
  items = [
    { id: 1, name: 'Item 1' },
    { id: 2, name: 'Item 2' },
    // ... list of items
  ];

  // TrackBy function to return a unique identifier for each item
  trackById(index, item) {
    return item.id;
  }
}
This Angular component uses the ngFor directive with a trackBy function. The trackById function is provided to ngFor to return a unique identifier (the id property) for each item. This prevents unnecessary DOM re-rendering when the list of items is updated, as long as the item's identity (as determined by the id) has not changed.