Sub topic 10
Conditionals and Lists with @if and @for
Real interfaces change shape with data. A list can be empty, a user can be logged in or not, and an order can be pending, shipped or cancelled. Angular templates handle these cases with built-in control flow blocks: @if, @for and @switch. They are part of the template syntax, so you do not import anything to use them.
This chapter assumes you can already build a standalone component, write interpolation ({{ }}), property binding ([prop]) and event binding ((event)), and read a signal by calling it, as in count(). Signals and component inputs each get their own chapter later. Here they only supply data to the templates.
Why Blocks Replaced Structural Directives
Older Angular code uses the structural directives *ngIf, *ngFor and [ngSwitch] for this job. They work, but they have drawbacks:
- You must import them through
CommonModuleor as individual directives into every standalone component. elsebranches need a separate<ng-template>with a template reference variable.*ngFormakestrackByoptional, so many apps re-create DOM nodes they could have reused.
The block syntax (stable since Angular 17) is compiled straight into the template instructions. It needs no imports, reads like ordinary code, and requires a tracking expression for every loop. The CLI generates new projects that use blocks, and ng generate @angular/core:control-flow migrates existing templates.
| Task | Legacy directive | Built-in block |
|---|---|---|
| Conditional | `*ngIf="cond; else other"` | `@if (cond) { } @else { }` |
| Loop | `*ngFor="let x of xs; trackBy: fn"` | `@for (x of xs; track x.id) { }` |
| Empty list | manual `*ngIf` check | `@empty { }` |
| Multi-branch | `[ngSwitch]` + `*ngSwitchCase` | `@switch (v) { @case (a) { } }` |
| Import needed | Yes | No |
Conditionals with @if
An @if block renders its content only when the expression is truthy. You can chain @else if and finish with @else:
@if (stock() > 10) {
<span class="ok">In stock</span>
} @else if (stock() > 0) {
<span class="low">Only {{ stock() }} left</span>
} @else {
<span class="out">Sold out</span>
}When a condition turns false, Angular removes that branch's elements from the DOM and destroys any components inside it. Hiding with CSS is different because the elements stay in the page. The difference matters: component state inside a removed branch is lost, and the components are created again from scratch when the branch comes back.
Aliasing the result with `as`
Often the condition is a value you want to use inside the block, such as a user that may be null. The as clause stores the result of the expression under a local name:
@if (currentUser(); as user) {
<p>Welcome back, {{ user.name }}</p>
} @else {
<button (click)="login()">Log in</button>
}Inside the block, user has the narrowed, non-null type, so strict template type checking accepts user.name. You can only use as on the first @if. It is not allowed on @else if.
Lists with @for
@for repeats its content once per item in an iterable, such as an array, a Map or a Set:
<ul>
@for (task of tasks(); track task.id) {
<li>{{ task.title }}</li>
} @empty {
<li>No tasks yet.</li>
}
</ul>The optional @empty block renders when the collection has no items. It removes the most common use of a separate @if around a list.
The track expression
The track clause is required. If you leave it out, compilation fails. Angular uses the tracking key to match each item to the DOM nodes it rendered last time. When the array changes, Angular compares old and new keys and then:
- keeps and moves nodes whose key still exists,
- creates nodes for new keys,
- destroys nodes for keys that disappeared.
How you choose the key decides how well this works:
| Track expression | When to use it | Risk |
|---|---|---|
| `track item.id` | Objects with a stable unique id (most data from an API) | None, if ids really are unique |
| `track item` | Primitives such as strings or numbers, or object references that stay the same | Refetched objects are new references, so every row is rebuilt |
| `track $index` | Static lists that never reorder, insert or delete | Reordering moves the data but not the DOM state, so focus, inputs and animations end up on the wrong row |
If two items produce the same key, Angular logs a duplicate-key warning (NG0955) in development mode. If one change makes Angular destroy and re-create the whole collection, it logs NG0956. That warning usually means you tracked by object identity on data that was fetched again.
Contextual variables
Inside @for, Angular provides implicit variables about the current iteration:
| Variable | Meaning |
|---|---|
| `$index` | Zero-based position of the item |
| `$count` | Total number of items |
| `$first` | `true` for the first item |
| `$last` | `true` for the last item |
| `$even` | `true` when `$index` is even |
| `$odd` | `true` when `$index` is odd |
You can use them directly or rename them with let. Renaming helps with nested loops, where an inner $index would otherwise hide the outer one:
@for (group of groups(); track group.id; let g = $index) {
@for (item of group.items; track item.id; let i = $index) {
<span>{{ g }}.{{ i }} {{ item.label }}</span>
}
}Multi-Way Branching with @switch
When one value picks between several templates, @switch reads more clearly than a long @else if chain:
@switch (order().status) {
@case ('pending') { <span>Awaiting payment</span> }
@case ('shipped') { <span>On its way</span> }
@case ('delivered') { <span>Delivered</span> }
@default { <span>Unknown status</span> }
}Angular compares the values with ===. Cases never fall through, so there is no break. @default is optional.
A Complete Example
The component below uses all three blocks. Put it in src/app/task-board.ts and add <app-task-board /> to your root template, with TaskBoard listed in the root component's imports array.
import { Component, computed, signal } from '@angular/core';
type Priority = 'high' | 'normal' | 'low';
interface Task {
id: number;
title: string;
done: boolean;
priority: Priority;
}
@Component({
selector: 'app-task-board',
template: `
<h2>Tasks ({{ remaining() }} remaining)</h2>
<button (click)="addTask()">Add task</button>
<button (click)="reverse()">Reverse order</button>
<button (click)="showDone.set(!showDone())">
{{ showDone() ? 'Hide' : 'Show' }} completed
</button>
<ul>
@for (task of visibleTasks(); track task.id; let i = $index, last = $last) {
<li [class.striped]="$even">
<input type="checkbox" [checked]="task.done" (change)="toggle(task.id)" />
{{ i + 1 }}. {{ task.title }}
@switch (task.priority) {
@case ('high') { <strong>(high)</strong> }
@case ('low') { <em>(low)</em> }
}
@if (last) { <small> — end of list</small> }
</li>
} @empty {
<li>Nothing to show.</li>
}
</ul>
@if (remaining() === 0 && tasks().length > 0) {
<p>All done!</p>
}
`,
styles: `.striped { background: #f3f3f3; }`,
})
export class TaskBoard {
private nextId = 4;
tasks = signal<Task[]>([
{ id: 1, title: 'Write the spec', done: true, priority: 'high' },
{ id: 2, title: 'Build the component', done: false, priority: 'normal' },
{ id: 3, title: 'Tidy the CSS', done: false, priority: 'low' },
]);
showDone = signal(true);
visibleTasks = computed(() =>
this.showDone() ? this.tasks() : this.tasks().filter((t) => !t.done),
);
remaining = computed(() => this.tasks().filter((t) => !t.done).length);
addTask() {
const id = this.nextId++;
this.tasks.update((list) => [
...list,
{ id, title: `Task ${id}`, done: false, priority: 'normal' },
]);
}
toggle(id: number) {
this.tasks.update((list) =>
list.map((t) => (t.id === id ? { ...t, done: !t.done } : t)),
);
}
reverse() {
this.tasks.update((list) => [...list].reverse());
}
}toggle builds a new object for the changed task, so its reference changes on every click. Because the loop tracks by task.id, Angular still reuses the existing <li> and only updates its bindings. Switch to track task and every toggle destroys and re-creates that row. Switch to track $index and click "Reverse order": the text moves, but if a checkbox has focus, the focus stays on the same position instead of following its task.
Common Errors
- Missing
track. The compiler reports that@forloops must have a "track" expression. Add one. - Using
ason@else if. This is not supported. Restructure the code or compute the value in acomputedsignal. - Forgetting to call signals.
@for (t of tasks; ...)iterates the signal function, not its value. Writetasks(). - Expecting
@ifto keep state. A branch that turns false destroys its components. To keep state, bind[hidden]or a CSS class instead. - Heavy expressions in conditions. Templates evaluate block expressions during change detection. Move filtering and sorting into
computed, asvisibleTasksdoes above, so the work runs only when its inputs change.
Exercise
A list of products comes from an API that is called again every 30 seconds, and each call returns new object instances with the same sku values. The template uses @for (p of products(); track p). What happens on each refresh, which warning might you see in development mode, and how do you fix it?
Show answer
Each refresh brings new object references, so no old key matches a new one. Angular destroys every row and creates it again, which loses DOM state and wastes work, and it may log NG0956. Track by the stable identifier instead: @for (p of products(); track p.sku).
Exercise
Rewrite this legacy template using built-in blocks: <p *ngIf="profile$ | async as profile; else loading">{{ profile.name }}</p><ng-template #loading>Loading…</ng-template>, assuming profile is now a signal that holds null until the data loads.
Show answer
@if (profile(); as p) { <p>{{ p.name }}</p> } @else { Loading… }. Neither CommonModule nor the async pipe is needed, and the else branch no longer needs an <ng-template> reference.
Exercise
In a nested loop, you need to show "row-column" coordinates such as 0-2. Why does {{ $index }}-{{ $index }} fail, and what is the fix?
Show answer
Inside the inner loop, $index refers to the inner loop's index and hides the outer one, so both numbers are the column. Rename them: @for (row of rows(); track row.id; let r = $index) { @for (cell of row.cells; track cell.id; let c = $index) { {{ r }}-{{ c }} } }.