Sub topic 6
Choosing a track expression
This chapter assumes you know TypeScript, Angular components and templates, and basic signals. It covers the track expression that every @for block requires: what it does, how to pick one, and which mistakes to avoid.
What track does
When the collection behind an @for block changes, Angular must decide which existing DOM nodes to keep, move, create, or destroy. The track expression gives each item an identity. Angular compares identities between the old and new collections.
- If an identity appears in both, Angular reuses that item's DOM nodes and updates their bindings.
- If an identity is new, Angular creates DOM nodes for it.
- If an identity disappears, Angular destroys its DOM nodes.
Reused nodes keep their state, such as focus, scroll position, text typed into an input, and running CSS transitions. With a poor identity, Angular tears down and rebuilds nodes that did not need to change.
Unlike *ngFor, where trackBy was optional, @for will not compile without track.
Tracking by a stable property
The best choice is a property that is unique per item and does not change, usually a database ID.
import { Component, signal } from '@angular/core';
interface Task {
id: number;
title: string;
}
@Component({
selector: 'app-task-list',
template: `
<button (click)="reload()">Reload</button>
<ul>
@for (task of tasks(); track task.id) {
<li>{{ task.title }} <input placeholder="Note" /></li>
} @empty {
<li>No tasks yet.</li>
}
</ul>
`,
})
export class TaskListComponent {
tasks = signal<Task[]>([
{ id: 1, title: 'Write spec' },
{ id: 2, title: 'Review pull request' },
]);
reload() {
// New objects, same ids.
this.tasks.set([
{ id: 1, title: 'Write spec' },
{ id: 2, title: 'Review pull request' },
]);
}
}Click Reload after typing in a note field. The objects are new, but the ids match, so Angular keeps the <li> elements and the typed text survives.
The three common choices
| Expression | Identity is | Use when |
|---|---|---|
| `track item.id` | A unique property | Items have a stable ID. This is the default choice. |
| `track item` | The object reference | Items are objects you keep, or primitives that are unique. |
| `track $index` | The position | The list is static, or never reordered or filtered. |
Tracking by object reference
track item compares items with strict equality. It works well when the same object instances persist across updates. If you replace every object, for example with fresh data from an HTTP call, every node is destroyed and recreated.
Tracking by $index
track $index ties identity to position. If you insert an item at the top, every item shifts position, so Angular updates the bindings of every existing node instead of moving one. It is acceptable for lists that never reorder, but it can cause stale state in inputs and components inside the list.
Pitfalls
- Duplicate identities. If two items produce the same track value, Angular cannot tell them apart. This causes wrong reuse and a development-mode warning. Pick a truly unique value.
- Unstable identities. An expression such as
track $indexon a reordered list, or one that calls a function returning a new value each time, defeats reuse. - Non-unique properties. Names, titles, and categories often repeat. Use an ID instead.
- Expensive expressions. Angular runs the expression for every item on every change, so keep it a simple property read.
Tracking primitives
For a list of unique strings or numbers, track the item itself.
import { Component, signal } from '@angular/core';
@Component({
selector: 'app-tag-list',
template: `
@for (tag of tags(); track tag) {
<span class="tag">{{ tag }}</span>
}
`,
})
export class TagListComponent {
tags = signal(['angular', 'signals', 'templates']);
}If the same string can appear twice, track tag produces duplicates. Track by index or by a generated ID in that case.
Exercise
A list of orders is fetched again every 30 seconds. Each fetch returns brand-new objects, each with a unique orderId, and users can sort the list and type notes into each row. Which track expression should you use, and why do track order and track $index both cause problems?
Show answer
Use track order.orderId. It stays the same across fetches and sorting, so Angular reuses each row and the typed notes stay with the right order. track order compares references, and every fetch produces new objects, so all rows are destroyed and recreated and typed notes are lost. track $index ties identity to position, so after sorting, each row's DOM node (and its typed note) belongs to a different order.