Sub topic 12
Rendering lists efficiently with track
This chapter assumes you can already build a FormArray of FormGroups and bind it with formArrayName and [formGroupName]="i". It covers what track does in the @for block, which tracking expression to choose for form rows, and what goes wrong when you choose badly.
Why @for requires track
Every time the controls array changes, Angular has to decide which DOM nodes to keep, create, move or destroy. The track expression gives each item a key, and Angular compares keys between the old and new list:
- A key that appears in both lists keeps its DOM nodes, including focus, text selection, scroll position and the state of the directives inside.
- A key that appears only in the new list gets new DOM nodes.
- A key that appears only in the old list has its DOM nodes destroyed.
The old *ngFor tracked by object identity unless you supplied trackBy. The @for block makes you choose, and omitting track is a compile error. For a plain list of strings the choice rarely matters. For form rows it determines whether a user keeps focus in the field they are typing in.
Track the control object
In a FormArray, each entry is its own FormControl or FormGroup object. That object is created once and stays the same until you remove it, so its identity makes a stable key:
import { Component, inject } from '@angular/core';
import { NonNullableFormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
@Component({
selector: 'app-line-items',
standalone: true,
imports: [ReactiveFormsModule],
template: `
<form [formGroup]="form">
<div formArrayName="items">
@for (item of items.controls; track item; let i = $index) {
<div [formGroupName]="i">
<input formControlName="name" placeholder="Name" />
<button type="button" (click)="remove(i)">Remove</button>
</div>
}
</div>
<button type="button" (click)="add()">Add</button>
</form>
`,
})
export class LineItemsComponent {
private fb = inject(NonNullableFormBuilder);
form = this.fb.group({
items: this.fb.array([this.createItem()]),
});
get items() {
return this.form.controls.items;
}
createItem() {
return this.fb.group({ name: ['', Validators.required] });
}
add() {
this.items.push(this.createItem());
}
remove(index: number) {
this.items.removeAt(index);
}
}With track item, removing the second of five rows destroys exactly one block of DOM. The other four rows keep their elements, their focus and their cursor positions. Their $index values are updated in place, so [formGroupName]="i" still resolves to the correct group.
What goes wrong with track $index
track $index tells Angular that the row at position 2 is always the same row. After you remove row 1 of 5, Angular does not remove that row's DOM. It reuses the existing blocks at positions 0 to 3 and destroys the block at position 4. Each reused block gets a new formGroupName value and rebinds to a different group.
Reactive forms recover the values this way, so the data stays correct. The problems are in what lives outside the control:
- Focus and selection stay on the DOM element at that position, which now shows a different row.
- Local state in child components, such as an expanded panel or an open dropdown, stays at the position and does not follow the row.
- CSS animations and transitions play on the wrong elements.
- Every row after the removed one is rebound, so the work scales with the list length.
| Expression | Stable when rows are removed or reordered | Typical use with a FormArray |
|---|---|---|
| `track item` (the control) | Yes | Default choice for rows created in the form |
| `track $index` | No | Static lists that never change order or length |
| `track item.controls.id.value` | Yes | Rows that carry a stable id from the server |
| `track item.value.name` | No, changes as the user types | Avoid |
Never track a value the user edits
Tracking by a field value looks reasonable until someone types in that field. Suppose the template says track item.value.name. Each keystroke changes the key, so Angular treats the row as removed and a new row as added. It destroys the input and creates a fresh one, and the user loses focus after every character.
Only track by values that never change while the row exists. Two options work:
- Track the control object, as above.
- Store a stable id in the group and track that.
The second option is useful when you rebuild the array from server data, because you can keep DOM nodes across a reload if the ids match:
import { Component, inject } from '@angular/core';
import { NonNullableFormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
interface Line {
id: string;
name: string;
}
@Component({
selector: 'app-keyed-lines',
standalone: true,
imports: [ReactiveFormsModule],
template: `
<form [formGroup]="form">
<div formArrayName="lines">
@for (line of lines.controls; track line.controls.id.value; let i = $index) {
<div [formGroupName]="i">
<input formControlName="name" />
</div>
}
</div>
</form>
`,
})
export class KeyedLinesComponent {
private fb = inject(NonNullableFormBuilder);
form = this.fb.group({
lines: this.fb.array<ReturnType<KeyedLinesComponent['createLine']>>([]),
});
get lines() {
return this.form.controls.lines;
}
createLine(line: Line = { id: crypto.randomUUID(), name: '' }) {
return this.fb.group({
id: [line.id],
name: [line.name, Validators.required],
});
}
load(data: Line[]) {
this.lines.clear();
data.forEach((d) => this.lines.push(this.createLine(d)));
}
}The id control is never bound to an input, so no user can change it. Its value is still part of the group, so it appears in getRawValue() and is sent back with the data on submit.
Be aware of a limit here. load calls clear() and then pushes brand-new group objects. The keys match the old ones, so Angular keeps the DOM blocks. The directives inside, such as formGroupName, rebind to the new groups, so their values update. Focus is usually preserved, but the user's in-progress edits are replaced by the loaded data, as you would expect.
Reordering without recreating rows
A FormArray has no move method. To reorder, remove the control and insert the same object at the new position:
move(from: number, to: number) {
const control = this.items.at(from);
this.items.removeAt(from);
this.items.insert(to, control);
}Because the control object is the same, track item produces the same key before and after. Angular moves the existing DOM block instead of destroying it, so focus, animations and child component state travel with the row. If you instead created a new group with the same values, the key would change and Angular would destroy and rebuild the row.
Duplicate keys
Keys must be unique within one list. Two entries with the same key confuse the diffing, and in development mode Angular logs a warning about duplicate keys. Tracking the control object cannot produce duplicates, because you would have to push the same object into the array twice. Tracking an id can, for example when the server returns repeated ids or when you copy a row by cloning its id. Generate a new id whenever you duplicate a row.
Cost of large lists
Choosing the right key avoids unnecessary DOM work, but a long FormArray has other costs that track does not address:
- Each
push,removeAtorinsertrecalculates the validity and value of the array and its parents. Adding 500 rows in a loop triggers 500 recalculations and 500valueChangesemissions. - Every keystroke in any row updates the value of the whole form.
For bulk loads, suppress events on each call and recalculate once at the end:
load(data: Line[]) {
this.lines.clear({ emitEvent: false });
data.forEach((d) => this.lines.push(this.createLine(d), { emitEvent: false }));
this.lines.updateValueAndValidity();
}For rows with many fields, you can also create each group with updateOn: 'blur', so values propagate when the user leaves a field instead of on every keystroke. Past a few hundred rows, consider paging or a virtual scroll list, because each row still holds real DOM and live directives.
Choosing an expression
- If rows exist only inside the form and you create them with
pushorinsert, usetrack item. - If rows come from a server and you rebuild the array on reload, store the server id in an unbound control and track
item.controls.id.value. - Use
track $indexonly when the list is fixed in length and order. - For bulk loads, pass
{ emitEvent: false }and callupdateValueAndValidity()once.
Exercise
A FormArray of FormGroups is rendered with @for (row of rows.controls; track row.value.label; let i = $index), where label is an input the user edits. Users report that the label field loses focus after every keystroke. Explain why, and give a fix.
Show answer
The key is the current value of label. Each keystroke changes the key, so Angular treats the old row as removed and a new row as added, destroying the focused input and creating a new one. Fix it by tracking something that does not change while the row exists: either the control object with track row, or a stable id stored in an unbound control with track row.controls.id.value.
Exercise
You move a row from index 3 to index 0 by calling removeAt(3) and then insert(0, this.rows.at(3)). The row loses its focus and its expanded panel closes, even though you track the control object. What is the bug, and how do you correct it?
Show answer
After removeAt(3), index 3 refers to a different control (or nothing), so the code inserts the wrong object. A correct move reads the control first: const c = this.rows.at(3); this.rows.removeAt(3); this.rows.insert(0, c);. Reinserting the same object keeps its track key, so Angular moves the existing DOM block and the focus and panel state travel with it.