Sub topic 2
Rendering Lists with `@for`
This chapter assumes Angular components, TypeScript interfaces, templates, and basic signals. Angular’s @for block renders one template instance for each item in a collection.
Rendering lists with `@for`
Use of to provide the collection and track to identify each item.
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 }}</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' },
]);
}Choosing a track expression
The track expression tells Angular which rendered DOM node belongs to which item. Angular can then reuse existing nodes when the collection changes.
Prefer a stable, unique property such as task.id.
| Collection | Suitable tracking expression |
|---|---|
| Objects with database IDs | `track task.id` |
| Primitive values | `track item` |
| No stable identity | `track $index` |
Avoid track $index when items can be inserted, removed, or reordered. Indexes describe positions, not items, so Angular may reuse the wrong DOM state.
Using implicit variables
Angular provides contextual variables inside @for.
| Variable | Meaning |
|---|---|
| `$index` | Zero-based item position |
| `$count` | Total item count |
| `$first`, `$last` | Whether the item is first or last |
| `$even`, `$odd` | Whether the index is even or odd |
Create shorter names with let:
@for (task of tasks(); track task.id; let i = $index, last = $last) {
<li>
{{ i + 1 }}. {{ task.title }}@if (!last) { <span>,</span> }
</li>
}Handling empty collections with `@empty`
Place @empty after the loop body. Angular renders it only when the collection has no items. This is clearer than adding a separate conditional around the list.
Exercise
Why is track task.id safer than track $index when tasks can be reordered?
Show answer
The ID stays with the task, while the index changes when positions change.