Sub topic 7
Conditionals and Lists with @if, @for, and @switch
Most real templates need to show different markup depending on state and repeat markup for every item in a collection. Angular's built-in control flow blocks, @if, @for, and @switch, handle both jobs directly in the template syntax. This chapter assumes you can already write a standalone component, read signals in a template, and use interpolation and event binding, all covered in earlier chapters.
Why Built-In Blocks
Control flow blocks are part of the template compiler. You do not import anything to use them. This is different from the older structural directives *ngIf, *ngFor, and *ngSwitch, which had to be imported from @angular/common. The blocks type-check better: inside @if (user(); as u), the compiler narrows u to a non-null type. They also run faster in @for, because tracking is required and the diffing algorithm is simpler.
Conditionals with @if
An @if block renders its content when the expression is truthy. You can chain @else if and finish with @else:
import { Component, signal } from '@angular/core';
interface User {
name: string;
isAdmin: boolean;
}
@Component({
selector: 'app-greeting',
template: `
@if (loading()) {
<p>Loading…</p>
} @else if (user(); as u) {
<p>Welcome back, {{ u.name }}.</p>
@if (u.isAdmin) {
<a href="/admin">Admin panel</a>
}
} @else {
<button (click)="logIn()">Log in</button>
}
`
})
export class GreetingComponent {
loading = signal(false);
user = signal<User | null>(null);
logIn() {
this.user.set({ name: 'Ada', isAdmin: true });
}
}The as u clause stores the expression's result in a local variable. You get two benefits from it. The signal is read only once, and u is typed as User instead of User | null inside the block. The alias is scoped to its own branch, so you cannot use u in the @else branch.
When a condition turns false, Angular destroys the DOM nodes and any components inside the block. When it turns true again, Angular creates them fresh. Any state held inside those components, such as typed-in form text, is lost. If you only want to hide something visually and keep its state, bind a class or style instead (covered in a later chapter).
Lists with @for
@for repeats its content for each item in an iterable. Arrays are the usual case, but any JavaScript iterable works, including Map and Set. The track expression is mandatory:
import { Component, signal } from '@angular/core';
interface Task {
id: number;
title: string;
}
@Component({
selector: 'app-task-list',
template: `
<button (click)="reverse()">Reverse</button>
<button (click)="clear()">Clear</button>
<ol>
@for (task of tasks(); track task.id; let i = $index, last = $last) {
<li [class.final]="last">
{{ i + 1 }}. {{ task.title }}
<input placeholder="Notes" />
</li>
} @empty {
<li>No tasks yet.</li>
}
</ol>
`,
styles: `.final { font-weight: bold; }`
})
export class TaskListComponent {
tasks = signal<Task[]>([
{ id: 1, title: 'Write tests' },
{ id: 2, title: 'Fix bug' },
{ id: 3, title: 'Deploy' }
]);
reverse() {
this.tasks.update(list => [...list].reverse());
}
clear() {
this.tasks.set([]);
}
}Type something into a Notes field and click Reverse. The text moves with its task, because track task.id tells Angular that the <li> for id 1 is the same row before and after the change. Angular moves the existing DOM nodes instead of rebuilding them.
What track does
The track expression gives each item a stable identity. When the collection changes, Angular compares old keys with new keys:
Choose the key carefully:
| Track expression | Behavior | When to use |
|---|---|---|
| `track item.id` | Rows follow their data across reorders, inserts, and deletes | Items with a unique, stable identifier (the normal case) |
| `track item` | Identity by object reference | Primitive lists such as strings, or objects that are never recreated |
| `track $index` | Identity by position | Static lists that never reorder, or lists with no identity at all |
track $index is a common mistake with stateful rows. If you delete the first item, the row at index 0 now shows the second item's data, but it keeps the first row's DOM state, such as focus, input text, or a running animation. track item breaks in a different way when data comes from an API. Each refetch produces new objects, so every row is destroyed and recreated even when nothing changed.
Contextual variables
Inside @for, Angular provides these implicit variables:
| Variable | Meaning |
|---|---|
| `$index` | Zero-based index of the current item |
| `$count` | Length of the collection |
| `$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 ({{ $index }}) or alias them with let, as in let i = $index, last = $last. You need aliases when you nest loops, because an inner $index hides the outer one:
import { Component } from '@angular/core';
@Component({
selector: 'app-grid',
template: `
@for (row of rows; track $index; let r = $index) {
@for (cell of row; track $index) {
<span>[{{ r }},{{ $index }}] {{ cell }}</span>
}
<br />
}
`
})
export class GridComponent {
rows = [['a', 'b'], ['c', 'd']];
}Tracking by $index is fine here because the grid never changes.
The @empty block is optional. It renders when the collection has no items, so you do not need a separate @if (list.length === 0) check.
Choosing One Branch with @switch
@switch picks one @case by comparing values with ===. The optional @default renders when no case matches:
import { Component, signal } from '@angular/core';
type Status = 'pending' | 'shipped' | 'delivered';
@Component({
selector: 'app-order-status',
template: `
@switch (status()) {
@case ('pending') { <p>Waiting for payment.</p> }
@case ('shipped') { <p>On its way.</p> }
@case ('delivered') { <p>Delivered. Enjoy!</p> }
@default { <p>Unknown status.</p> }
}
<button (click)="advance()">Next step</button>
`
})
export class OrderStatusComponent {
status = signal<Status>('pending');
advance() {
const next: Record<Status, Status> = {
pending: 'shipped',
shipped: 'delivered',
delivered: 'pending'
};
this.status.update(s => next[s]);
}
}Two details catch people coming from JavaScript switch. Cases do not fall through, so each case renders only its own block, and you never write break. Comparison is strict, so @case (1) does not match the string '1', which is a common bug when the value comes from a URL parameter or a form field.
Use @switch when one expression maps to several mutually exclusive views. Use @if/@else if when the branches test different conditions.
Common Errors
| Symptom | Cause | Fix |
|---|---|---|
| Compile error: `@for loop must have a "track" expression` | `track` was omitted | Add `track item.id` or a suitable key |
| Input text or focus jumps to the wrong row | `track $index` on a reorderable list | Track by a stable id |
| Whole list re-renders after every fetch | `track item` with freshly created objects | Track by id |
| Alias is undefined in `@else` | `as` variables exist only in their own branch | Restructure, or read the signal again |
| `@case` never matches | Type mismatch under `===` | Convert the value, for example `Number(param)` |
| Child component loses state on toggle | `@if` destroys and recreates the content | Hide with a class binding instead |
Exercise
A list of chat messages is rendered with @for (msg of messages(); track $index). Each row contains an "edit" text field. When a new message is inserted at the top, the text a user was typing appears next to a different message. Explain why and give the fix.
Show answer
With track $index, Angular identifies rows by position. Inserting at the top shifts every item down one index, so the DOM row at index 0, which holds the typed text, is reused for the new message. The data changes but the DOM state stays put. Tracking by a stable key such as track msg.id makes each row follow its message, and the new message gets a newly created row.
Exercise
Write a template fragment that renders a list of products() as <li> elements showing the product name, adds the class stripe on odd rows, shows "Out of stock" when products() is empty, and finally prints "Showing N products" using a contextual variable on the last row only.
Show answer
@for (p of products(); track p.id; let odd = $odd, last = $last, n = $count) { <li [class.stripe]="odd">{{ p.name }}</li> @if (last) { <li>Showing {{ n }} products</li> } } @empty { <li>Out of stock</li> }. The $odd, $last, and $count variables are aliased so they read clearly, and @empty handles the empty case without a separate @if.
Exercise
A route parameter gives you level = signal(this.route.snapshot.paramMap.get('level')), and the template uses @switch (level()) { @case (1) {...} @case (2) {...} @default {...} }. Only the default block ever renders. Why?
Show answer
paramMap.get returns a string such as '1', and @switch compares with ===, so '1' === 1 is false. Either convert the value when creating the signal, for example signal(Number(...)), or write the cases as strings: @case ('1').