0
0
Angularframework~5 mins

TrackBy in ngFor in Angular

Choose your learning style9 modes available
Introduction

TrackBy helps Angular remember items in a list to update only what changes. This makes your app faster and smoother.

When displaying a list of items that can change often, like messages or tasks.
When you want to avoid flickering or losing input focus in list items during updates.
When working with large lists to improve performance by reducing DOM updates.
When items have unique IDs you can use to track them efficiently.
Syntax
Angular
<div *ngFor="let item of items; trackBy: trackByFunction">{{item.name}}</div>

trackByFunction(index: number, item: any): any {
  return item.id;
}

The trackBy function receives the index and the item from the list.

It should return a unique identifier for each item, usually an ID.

Examples
Tracks users by their unique id property.
Angular
<div *ngFor="let user of users; trackBy: trackByUserId">{{user.name}}</div>

trackByUserId(index: number, user: any): number {
  return user.id;
}
Tracks products by their position in the list (index). Useful if no unique ID exists.
Angular
<div *ngFor="let product of products; trackBy: trackByIndex">{{product.name}}</div>

trackByIndex(index: number, product: any): number {
  return index;
}
Sample Program

This component shows a list of products. Clicking the button shuffles the list order. Using trackById helps Angular keep track of each product by its id, so it only updates the order without recreating all list items.

Angular
import { Component } from '@angular/core';

@Component({
  selector: 'app-trackby-demo',
  template: `
    <h2>Product List</h2>
    <button (click)="shuffle()">Shuffle Products</button>
    <ul>
      <li *ngFor="let product of products; trackBy: trackById">
        {{product.name}} (ID: {{product.id}})
      </li>
    </ul>
  `
})
export class TrackByDemoComponent {
  products = [
    { id: 1, name: 'Apple' },
    { id: 2, name: 'Banana' },
    { id: 3, name: 'Cherry' }
  ];

  trackById(index: number, product: any): number {
    return product.id;
  }

  shuffle() {
    this.products = this.products
      .map(value => ({ value, sort: Math.random() }))
      .sort((a, b) => a.sort - b.sort)
      .map(({ value }) => value);
  }
}
OutputSuccess
Important Notes

Without trackBy, Angular recreates all list items on changes, which can cause flicker and lose input focus.

Always use a unique and stable identifier for best results.

Summary

TrackBy improves list rendering performance by identifying items uniquely.

Use it when lists update often or are large.

It helps Angular update only changed items, making apps faster and smoother.