← Back to Angular, page 9

angular-0168 · Medium mid

How does the track expression in @for affect performance and DOM reuse, and how can you measure the difference when a list is replaced with fresh data?

When the array is replaced with new objects, track $index or track item (object identity) reuses or recreates DOM based on position or reference. Tracking a stable id keeps the existing DOM elements for rows whose id remains, so only changed rows update. The difference shows as created or destroyed elements and lost input state.

Full answer

@for (row of rows(); track row.id) tells Angular how to match old items to new items when the array changes. Matching items keep their DOM nodes and component instances. Unmatched items are created or destroyed. This is both a performance and a correctness feature.

Consider a table loaded again from the server every few seconds. Each response gives new objects, with the same ids and mostly the same data.

  • track row (object identity): all objects are new, so no item matches. Angular destroys all old rows and creates all new ones. This is the slowest option, and the user loses focus, selection and text typed in a row's input.
  • track $index: the item at position 3 is matched with the new item at position 3. DOM nodes are reused and bindings update. This is fast for a fixed list. But if rows are inserted or removed at the top, every position shifts, so every row updates, and component state such as an input value stays with the position, not with the data row.
  • track row.id: matches by the stable key. If a row moved, Angular moves its DOM node. If a row is new, one node is created. Only rows with changed data update their bindings. This is the right default for lists of records.

Rules for a good key: unique inside the list, stable across reloads, and not changing when data changes. A duplicate key causes a development warning and wrong reuse. track $index is acceptable for static lists that never reorder, or for simple text rows.

How to measure: count created DOM nodes using a MutationObserver on the list (added and removed nodes), or keep a reference to a row element before the update and check it afterwards (sameNode). Add ngOnInit and ngOnDestroy counters in a row component. Use the Angular DevTools profiler or the browser Performance panel for time on large lists (1000 rows or more).

Beyond track: virtual scrolling for very long lists, pagination, and OnPush row components so unchanged rows are skipped.

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

// Captured counts (Karma, Angular 20.3) with 5 rows:
//   reload with new objects, same ids:  track object -> 5 created, 5 destroyed
//                                       track $index -> 0 created, 0 destroyed
//                                       track id     -> 0 created, 0 destroyed
//   insert a row at the top:            track object -> 6 created, 5 destroyed
//                                       track $index -> 1 created, 0 destroyed, and the first DOM node now shows "Student 0"
//                                       track id     -> 1 created, 0 destroyed, and the first DOM node still shows "Student 1"
export const rowStats = { created: 0, destroyed: 0 };

@Component({ selector: 'app-row', template: `{{ label() }}` })
export class RowComponent implements OnInit, OnDestroy {
  readonly label = input.required<string>();
  ngOnInit(): void { rowStats.created++; }
  ngOnDestroy(): void { rowStats.destroyed++; }
}

interface Student { id: number; name: string }

@Component({
  selector: 'app-track-demo',
  imports: [RowComponent],
  template: `
    @switch (mode()) {
      @case ('object') { @for (s of students(); track s) { <app-row [label]="s.name" /> } }
      @case ('index') { @for (s of students(); track $index) { <app-row [label]="s.name" /> } }
      @case ('id') { @for (s of students(); track s.id) { <app-row [label]="s.name" /> } }
    }
  `,
})
export class TrackDemoComponent {
  readonly mode = signal<'object' | 'index' | 'id'>('id');
  readonly students = signal<Student[]>([]);

  load(): void {
    // A "server response": new objects with the same ids.
    this.students.set([1, 2, 3, 4, 5].map((id) => ({ id, name: `Student ${id}` })));
  }

  reloadWithNewFirstRow(): void {
    this.students.set([0, 1, 2, 3, 4, 5].map((id) => ({ id, name: `Student ${id}` })));
  }
}

Angular 20.3, strict template check passes. A Karma test reloads the list with new objects and inserts a row at the top, for each tracking mode. The captured counts are in the comment.

Key points

  • `track` matches old and new items. Matches keep DOM and state.
  • With fresh objects, `track item` recreates everything. `track $index` reuses by position. `track id` reuses by identity of the record.
  • Keys must be unique and stable.
  • Measure with created and destroyed counters, or the profiler.

Common mistakes

  • Using `track row` (the object) when data is reloaded from the server.
  • Using `track $index` on a list where rows are inserted at the top.
  • Using a non-unique key such as the name.

Follow-ups

  • What happens in development mode if keys are duplicated?
  • How would you keep a selected row after a refresh?
  • When is `track $index` the right choice?

Tips

  • Describe the refresh scenario first.
  • Mention lost input state, not only speed.
  • Offer a way to measure.

Evaluation rubric

  • Explains matching by key for the three choices.
  • Gives rules for a good key.
  • Measures the effect with real counters.