Blog>
Snippets

Unidirectional Data Flow with NgFor TrackBy

Explains how to use the trackBy function with *ngFor to maintain a stable DOM and efficient rendering, thus respecting Angular's unidirectional data flow.
import { Component } from '@angular/core';

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

  trackById(index, item) {
    return item.id;
  }
}
This Angular component uses the *ngFor directive with a trackBy function to iterate over a list of items. The trackById method is used to provide a unique identifier for each item. This allows Angular to track which items have changed and only re-render those items, improving performance and maintaining a stable DOM. The trackBy function receives the index and the current item as arguments and returns a unique identifier, typically the item's ID. This is particularly useful when the list of items may change dynamically.