Menu
×
   ❮     
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL MONGODB ASP AI R GO KOTLIN SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING BASH RUST

Angular Templates: TrackBy with *ngFor


Keep lists fast and stable by identifying items with a unique key via trackBy.


What is TrackBy with *ngFor?

  • Defines how Angular identifies list items.
  • Enables DOM node reuse when items move, insert, or remove.
  • Typically returns a unique ID for each item.

When to use TrackBy

  • Lists that are frequently reordered, inserted, or removed.
  • To avoid unnecessary re-rendering and improve performance.
  • When items have stable, unique identifiers.

Details and examples: Lists (*ngFor, trackBy).

Example

import { bootstrapApplication } from '@angular/platform-browser';
import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';

type Item = { id: number; name: string };

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [CommonModule],
  template: `
    <button (click)="shuffle()">Shuffle</button>
    <ul>
      <li *ngFor="let it of items; trackBy: trackById">{{ it.id }} - {{ it.name }}</li>
    </ul>
  `
})
export class App {
  items: Item[] = [
    { id: 1, name: 'Alpha' },
    { id: 2, name: 'Beta' },
    { id: 3, name: 'Gamma' }
  ];
  shuffle() {
    this.items = [...this.items].reverse();
  }
  trackById(_i: number, it: Item) { return it.id; }
}

bootstrapApplication(App);
<app-root></app-root>

Run Example »

Example explained

  • *ngFor ... trackBy: trackById: Uses trackById to give each item a stable identity so Angular can reuse DOM nodes when the list order changes.
  • trackById(index, item): Returns the unique key for an item. Here, it returns item.id regardless of index.
  • shuffle(): Reverses the array to demonstrate that with trackBy, Angular moves existing DOM nodes instead of destroying and recreating them.


×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2025 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.