Sub topic 5
Rendering lists with @for
This chapter covers the @for block: its syntax, what it iterates over, and how it renders each item. It stays on the basic form and leaves the details of track, the implicit variables, and @empty to the chapters that follow.
Prerequisites assumed: basic TypeScript, Angular components and templates, interpolation and property binding, and some familiarity with signals. You should know what @if does from the earlier chapters.
What @for does
@for repeats a block of template once for each item in a collection. It replaces *ngFor. It is part of the template syntax itself, so you do not import NgFor or CommonModule to use it.
The general shape is:
@for (item of collection; track expression) {
...content repeated for each item...
}Two parts are required: the item of collection clause and the track expression. If you leave out track, the compiler reports an error. This is a deliberate difference from *ngFor, where trackBy was optional.
A first example
The component below renders a list of tasks from a signal.
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; let i = $index, isEven = $even) {
<li [class.striped]="isEven">{{ i + 1 }}. {{ task.title }}</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' },
]);
}Read the @for line from left to right:
task of tasks()declares a loop variable namedtask. The expressiontasks()reads the signal, so the block re-renders when the signal changes.track task.idtells Angular how to identify each item.let i = $index, isEven = $evencreates aliases for two implicit variables. These are optional.
The @empty block renders only when the collection has no items. Here it is shown so the example is complete.
What you can iterate over
The expression after of can be an array or any other iterable. Arrays are by far the most common case. Other iterables, such as a Set, a Map, or a generator result, also work.
import { Component } from '@angular/core';
@Component({
selector: 'app-tag-list',
template: `
@for (tag of tags; track tag) {
<span class="tag">{{ tag }}</span>
}
`,
})
export class TagListComponent {
tags = new Set(['angular', 'signals', 'templates']);
}Note that the loop variable is only in scope inside the block. Outside the closing brace, task and tag do not exist.
A null or undefined collection renders nothing and does not throw. This makes it safe to write @for (item of maybeItems; track item.id) when the data has not arrived yet. For a clear loading state, pair the loop with @if rather than relying on the empty rendering.
How @for decides what to render
When the collection changes, Angular compares the new items with the old ones using the track expression. For each item, the expression produces a key.
- If a key existed before, Angular reuses the DOM nodes for that item and updates their bindings.
- If a key is new, Angular creates new DOM nodes.
- If a key disappeared, Angular removes the matching nodes.
- If the order changed, Angular moves existing nodes instead of rebuilding them.
The outcome is that a good key keeps DOM state attached to the right item. That state includes the text a user typed in an input, focus, scroll position inside the item, and any running animation or child component state.
flowchart TDThe diagram above is replaced by the one below, which shows the comparison in full.
A quick look at track
The next chapter covers track in depth. Three rules are enough for now.
- Prefer a unique, stable identifier such as
task.id. - Use
track $indexonly for lists that never reorder, insert, or delete in the middle. With it, Angular identifies items by position. - Use
track itemfor lists of primitives such as strings or numbers when the values are unique.
Tracking by the object itself (track task) compares by reference. If your code replaces objects with fresh copies on every update, for example after a fetch, every node is destroyed and recreated.
Statements inside the block
The body of @for can contain anything a template can: elements, components, bindings, event handlers, and other control flow blocks. Each iteration gets its own copy of the content.
import { Component, signal } from '@angular/core';
interface Product {
sku: string;
name: string;
inStock: boolean;
}
@Component({
selector: 'app-products',
template: `
<ul>
@for (p of products(); track p.sku) {
<li>
{{ p.name }}
@if (p.inStock) {
<button (click)="remove(p.sku)">Remove</button>
} @else {
<em>Out of stock</em>
}
</li>
}
</ul>
`,
})
export class ProductsComponent {
products = signal<Product[]>([
{ sku: 'a-1', name: 'Keyboard', inStock: true },
{ sku: 'b-2', name: 'Monitor', inStock: false },
]);
remove(sku: string) {
this.products.update(list => list.filter(p => p.sku !== sku));
}
}Here remove produces a new array with filter. Because the key is p.sku, Angular removes only the one <li> that disappeared and leaves the others untouched.
Updating the collection
@for reacts to the collection you give it. With signals, replace the value with set or update, as remove does above. Mutating an array in place, for example with push, does not notify a signal, so the template does not update.
// Does not notify the signal: the view stays the same.
this.tasks().push({ id: 3, title: 'Deploy' });
// Notifies the signal: the view updates.
this.tasks.update(list => [...list, { id: 3, title: 'Deploy' }]);If the collection is a plain array property rather than a signal, Angular's change detection still picks up in-place changes when it checks the component, because the block inspects the iterable during rendering. Signals remain the clearer choice, particularly with OnPush components.
Comparison with *ngFor
| Aspect | `*ngFor` | `@for` |
|---|---|---|
| Import needed | `NgFor` or `CommonModule` | None |
| Tracking | Optional `trackBy` function | Required `track` expression |
| Empty fallback | `else` with an `ng-template` | `@empty` block |
| Index variable | `let i = index` | `let i = $index` |
| Extra wrapper | Structural directive on an element | Block, no host element needed |
Because @for is not a directive, you do not need an extra <ng-container> just to loop over several sibling elements. You can place any number of elements inside the block.
Common mistakes
- Leaving out
track. The template fails to compile. Add a key expression. - Using
track $indexon a list that reorders. Typed input and component state stay at the position rather than following the item. - Using
track itemon objects that are recreated. All nodes rebuild on every refresh. - Forgetting the parentheses on a signal.
@for (t of tasks; ...)iterates over the signal function object, not its value. Writetasks(). - Mutating the array in place. Create a new array so the signal notifies.
- Writing the old syntax.
*ngFor="let t of tasks"inside an@forblock works only ifNgForis imported, and it is almost always a mistake to mix them.
Summary
@for repeats a template for each item in an iterable. It needs no imports and requires a track expression so that Angular can reuse DOM nodes when the collection changes. A stable unique key keeps item state attached to the right row. With signals, update the collection by producing a new array.
Exercise
A component has items = signal<{ id: number; label: string }[]>([...]). A button handler runs this.items().push({ id: 9, label: 'New' }), and the list on screen does not change. Explain why, and write the fix. Then state which track expression you would choose and why.
Show answer
push mutates the array in place, and the signal's value is still the same array reference, so the signal does not notify the template. Use this.items.update(list => [...list, { id: 9, label: 'New' }]); to produce a new array. The template should use @for (item of items(); track item.id) { ... }. The id is unique and stable, so Angular keeps existing nodes and creates only one new node for the added item.
Exercise
What happens at compile time if you write @for (task of tasks(); ) { <li>{{ task.title }}</li> } with no track expression, and how does this differ from *ngFor without trackBy?
Show answer
The compiler reports an error because track is required in @for. With *ngFor, omitting trackBy is allowed and falls back to tracking by object identity, so the mistake could go unnoticed and hurt performance.