← Back to Angular, page 1

angular-0008 · Easy fresher

Why is the track expression required in @for, and what should you track?

track tells Angular how to match old list items to new ones, so it can reuse existing DOM nodes when the list changes instead of destroying and rebuilding them. Track a unique, stable identity such as an id. Track $index only for lists that never reorder.

Full answer

When the array behind a @for changes, Angular must decide which DOM nodes to keep, move, add, or remove. The track expression produces a key for each item. Items with the same key between two renders are treated as the same item, so Angular reuses its DOM and updates only what changed.

Without a stable key, Angular would have to rebuild the whole list when you receive fresh objects from an API, even if the data is the same. That loses input focus, scroll position inside rows, running animations, and costs time.

What to track:

  • A unique id from the data, for example track student.id. This is the best choice.
  • track $index is fine for a static list that never reorders, or for a simple list of primitives where the position is the identity.
  • track item (the object itself) works only if the same object references stay in the array. After an HTTP refresh, the new objects have new references, so everything rebuilds.

The old *ngFor had an optional trackBy function. Many projects never used it, so the new syntax makes the choice compulsory. In development mode Angular logs a warning when two items produce the same key.

An example: a class list in which students are re-sorted by marks. With track s.id, the rows move to new positions with their DOM intact. With track $index, the same row elements are reused and their text changes, so an input typed in row 2 would stay in row 2 even though the student moved.

typescript
import { Component, signal } from '@angular/core';

interface Student {
  id: number;
  name: string;
  marks: number;
}

@Component({
  selector: 'app-marks-table',
  template: `
    <button (click)="sort()">Sort by marks</button>
    <button (click)="reload()">Reload from server</button>
    <ul>
      @for (s of students(); track s.id) {
        <li>
          {{ s.name }}: {{ s.marks }}
          <input placeholder="note for {{ s.name }}" />
        </li>
      }
    </ul>
  `,
})
export class MarksTableComponent {
  students = signal<Student[]>([
    { id: 1, name: 'Asha', marks: 71 },
    { id: 2, name: 'Imran', marks: 88 },
    { id: 3, name: 'Meera', marks: 64 },
  ]);

  sort(): void {
    this.students.update((list) => [...list].sort((a, b) => b.marks - a.marks));
  }

  reload(): void {
    // New object instances with the same ids, as an API refresh would return.
    this.students.update((list) => list.map((s) => ({ ...s })));
  }
}

Angular 20.3. Try swapping `track s.id` for `track $index`, type a note in the first row, then press Sort, and watch where the typed text stays.

Key points

  • `track` gives each item an identity so DOM nodes can be reused.
  • Prefer a unique stable id, and avoid tracking whole objects from refreshed API data.
  • `track $index` is safe only for lists that do not reorder or change in the middle.
  • It is required in `@for`; `*ngFor` had an optional `trackBy`.

Common mistakes

  • Using `track $index` on a sortable list with inputs inside rows. Typed values stay at the old row position.
  • Tracking a field that is not unique, such as `name`. Duplicate keys cause wrong reuse and a development warning.
  • Using a function call that creates a new object or random value each time, which makes every item look new.

Follow-ups

  • What happens to the DOM if you track by `item` and replace the array with new objects each poll?
  • How would you track items that have no id?
  • How does `@for` behave with an empty array and `@empty`?

Tips

  • Give the sorted list with typed inputs example. It shows you understand the real effect.
  • Say what you would do if the API has no id: build a key from stable fields or add one when loading.
  • Mention that fewer DOM operations also help performance on large lists.

Evaluation rubric

  • Explains DOM reuse as the purpose.
  • Prefers a unique id and can name when $index is safe.
  • Knows the difference from ngFor trackBy.