Skip to the workspace
Pebellslearn by building
Template Syntax and Lifecycle  ›  Lesson

@for, track and @empty

@for 12 minThe @for block renders its content once per item in a collection, requires a track expression that identifies each item, and can show an @empty block when there are no items.

angular / @for, track and @empty

Explore each scene at your own pace.

01 · The rule

The rule

@for, track and @empty

Greenhouse shows a list of plants, and the list changes: plants are added, removed and watered many times a day. Angular must turn an array into elements, and then, on every change, work out which elements to keep. The @for block does both, as long as you tell it how to recognise each plant.

The rule

One block per item, tracked by something that never changes.

<ul>
  @for (p of plants(); track p.id) {
    <li [class.last]="$last">{{ $index + 1 }}. {{ p.name }}</li>
  } @empty {
    <li>No plants yet.</li>
  }
</ul>
  • p of plants() names each item p.
  • track p.id is required. It gives Angular a stable identity for each item.
  • @empty is optional and renders when the collection has no items.

Inside the block, Angular provides helpful values: $index, $first, $last, $even, $odd and $count. You can rename them if loops are nested: @for (p of plants(); track p.id; let i = $index).

Why is track required? When the array changes, Angular compares the tracked keys of the old and new items. Same key: reuse the existing element and just update its text. New key: create an element. Missing key: remove it. With a good key, watering one plant touches one <li>. With a bad key, Angular throws away and rebuilds rows, and any focus, scroll position or half-typed text inside them is lost.

What to track:

  • A unique id from your data. Best choice.
  • $index for a fixed list that never reorders, like a static list of weekdays.
  • Never a value that changes, such as p.lastWatered, and avoid the whole object when you replace objects with new copies.
Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.