Sub topic 6
Choosing a track expression
This chapter assumes you can write an Angular component with a template, bind to signals, and read basic TypeScript. You should also have seen the @for block from the previous chapter. Here we focus on one required part of it: the track expression.
What track does
When the collection behind an @for block changes, Angular has to decide which existing DOM nodes to keep, which to move, which to create, and which to destroy. The track expression gives each item an identity. Angular evaluates it for every item and compares the results between the old and new collection.
- If an identity appears in both the old and new collection, Angular reuses the existing view and updates its bindings. The view may move to a new position.
- If an identity appears only in the new collection, Angular creates a view.
- If an identity appears only in the old collection, Angular destroys that view.
Reusing a view keeps everything attached to it: focus, text typed into an input, scroll position inside the item, running animations, and the state of any child component.
import { Component, signal } from '@angular/core';
interface Task {
id: number;
title: string;
}
@Component({
selector: 'app-task-list',
template: `
<ul>
@for (task of tasks(); track task.id) {
<li>{{ task.title }} <input placeholder="Note" /></li>
} @empty {
<li>No tasks yet.</li>
}
</ul>
<button (click)="reverse()">Reverse</button>
`,
})
export class TaskListComponent {
tasks = signal<Task[]>([
{ id: 1, title: 'Write spec' },
{ id: 2, title: 'Review pull request' },
]);
reverse() {
this.tasks.update(list => [...list].reverse());
}
}Type a note in the first input and click Reverse. Because track task.id identifies each item, Angular moves the existing <li> elements. Your note stays with the task it belongs to.
Track is required
Unlike trackBy in *ngFor, track is mandatory. Omitting it is a compile-time error. The Angular team made it required because forgetting trackBy was a common source of poor performance, and a default that silently re-created the DOM was easy to miss.
<!-- Compile error: @for requires a track expression -->
@for (task of tasks(); ) {
<li>{{ task.title }}</li>
}Three common choices
A unique, stable property
This is the best choice for data that comes from a server or a database. An id, a UUID, or a natural key such as an email address works if it is unique within the collection and does not change for the life of the item.
@for (user of users(); track user.id) {
<app-user-card [user]="user" />
}The item itself
For primitives such as strings and numbers, or for objects whose references you keep stable, use track item. Angular compares the values using identity (===).
@for (tag of tags(); track tag) {
<span class="chip">{{ tag }}</span>
}This works only when the values are unique. Two equal strings in the same list produce duplicate identities (see the pitfalls below). For objects, it also means that a new object with the same content counts as a different item.
The index
track $index uses the position as the identity. Angular then reuses the view at each position and updates its bindings with whatever item is now there.
@for (n of numbers(); track $index) {
<li>{{ n }}</li>
}This is acceptable for static lists that never reorder, or for lists of primitives where recreating nothing is the goal and no per-row state exists. It is a poor choice when items can be inserted, removed, or reordered, because state stays at a position instead of following the item.
Comparing the options
| Expression | Identity is | Good for | Risk |
|---|---|---|---|
| `track item.id` | A unique key on the item | Server data, editable lists, reorderable lists | Duplicate or missing keys |
| `track item` | The value or object reference | Lists of unique primitives, stable object references | Replaced objects are re-created; duplicate values collide |
| `track $index` | The position | Static lists that never reorder | State sticks to the position, not the item |
What happens when data is replaced
A frequent pattern is to reload a list from an API. Every response contains brand-new objects, even if the data is unchanged.
import { Component, signal } from '@angular/core';
interface Product {
id: number;
name: string;
price: number;
}
@Component({
selector: 'app-products',
template: `
<button (click)="refresh()">Refresh</button>
<ul>
@for (p of products(); track p.id) {
<li>{{ p.name }}: {{ p.price }}</li>
}
</ul>
`,
})
export class ProductsComponent {
products = signal<Product[]>([
{ id: 1, name: 'Keyboard', price: 40 },
{ id: 2, name: 'Mouse', price: 20 },
]);
refresh() {
// Simulates a new API response: new objects, same ids.
this.products.set([
{ id: 1, name: 'Keyboard', price: 38 },
{ id: 2, name: 'Mouse', price: 20 },
]);
}
}With track p.id, Angular keeps both <li> elements and updates only the changed text. With track p, each new object has a new reference, so Angular destroys every <li> and creates new ones. For a list of two this is invisible. For hundreds of rows with child components, it causes visible cost and loses state.
The following diagram shows the decision Angular makes for each item.
Using a function for track
The expression can call a method on the component. The method receives the index and the item, as trackBy functions do.
import { Component, signal } from '@angular/core';
interface Row {
region: string;
code: string;
}
@Component({
selector: 'app-rows',
template: `
@for (row of rows(); track trackRow($index, row)) {
<p>{{ row.region }} / {{ row.code }}</p>
}
`,
})
export class RowsComponent {
rows = signal<Row[]>([
{ region: 'eu', code: 'a1' },
{ region: 'us', code: 'a1' },
]);
trackRow(index: number, row: Row): string {
return `${row.region}:${row.code}`;
}
}Use this when no single property is unique, such as when the key is a combination of fields. Angular optimizes the common expressions (item, item.prop, and $index) by recognizing their form. For other expressions, including method calls, it has to evaluate the call for each item on each change. Keep any function cheap and free of side effects.
Calls to a component method in track are also the one place where you need to write this-free code carefully: Angular calls methods referenced in track with the component instance as context, so they can read component fields, but relying on that makes the key depend on state that may change. Prefer a pure computation from the item.
Pitfalls
Duplicate track values
If two items yield the same track value, Angular logs a warning in development mode (NG0955) and the behavior is degraded: the views for duplicates are matched less predictably, and Angular may need to re-create views, which loses state. Fix the data or use a composite key.
<!-- tags() contains 'news' twice -->
@for (tag of tags(); track tag) { <!-- duplicate values: avoid -->
<span>{{ tag }}</span>
}
<!-- Safer: include the index when values can repeat -->
@for (tag of tags(); track tag + $index) {
<span>{{ tag }}</span>
}Including $index in the key means a repeated value no longer collides, but it also means that reordering changes every identity. Choose it only when the data really has no better key.
Unstable keys
A key must stay the same for the same logical item. Do not use Math.random(), crypto.randomUUID(), or Date.now() inside track. A new value on each evaluation makes every item look new, so every view is destroyed and rebuilt on every change.
<!-- Wrong: a new key on every change -->
@for (item of items(); track crypto.randomUUID()) { ... }If your data has no id, assign one once, when the item is created or loaded, and store it on the item.
Mutable keys
Tracking by a property that the user can edit, such as a title or name, makes the identity change when they type. The view is destroyed and re-created while they type, and the input loses focus. Track by an id that never changes.
Using the index with reordering
With track $index, if you remove the first item, every later item shifts position. Angular keeps all the views and rewrites their bindings, so the view that held row 2's typed text now shows row 1's data with that text still in the input. Switch to an id.
Choosing quickly
- Does each item have a unique id that never changes? Use
track item.id. - Is the list made of unique primitives? Use
track item. - Is the key a combination of fields? Use a function that builds a string from them.
- Is the list static and never reordered, with no per-row state?
track $indexis acceptable.
Exercise
A list of editable rows is rendered with @for (row of rows(); track row.name). The user can edit name in an input inside each row. What goes wrong while they type, and what should you track instead?
Show answer
The track value changes each time the name changes, so Angular treats the row as a new item. It destroys the old view and creates a new one, which drops the input's focus and any local state. Track a property that never changes for an item, such as a server-assigned id, for example track row.id.
Exercise
You use @for (n of numbers(); track $index) and then remove the first element. Describe how Angular updates the DOM, and why this can show wrong state in rows with their own inputs.
Show answer
The identity of each view is its position. After the removal, the view at position 0 is reused for the old second item, position 1 for the old third item, and the last view is destroyed. Angular only updates the bindings. Any state stored in a view, such as text typed into an input, stays at that position, so it now sits next to a different item. Tracking by a stable id makes Angular remove the view for the deleted item and keep the others.