Sub topic 3
Choosing Between Templates with `@switch`
This chapter assumes Angular components, templates, TypeScript unions, and basic property binding. Angular’s built-in control-flow blocks work directly in templates, so they do not require directive imports.
Choosing with `@switch`
Use @switch when one value determines which template to render. Each @case uses strict equality (===). Angular renders the first matching case and does not fall through to later cases. Use @default for unexpected or unhandled values.
import { Component, signal } from '@angular/core';
type Status = 'loading' | 'error' | 'ready';
@Component({
selector: 'app-status',
template: `
@switch (status()) {
@case ('loading') {
<p>Loading data...</p>
}
@case ('error') {
<p>Could not load the data.</p>
<button (click)="retry()">Try again</button>
}
@case ('ready') {
<p>Data is ready.</p>
}
@default {
<p>Unknown status.</p>
}
}
`,
})
export class StatusComponent {
status = signal<Status>('loading');
retry(): void {
this.status.set('loading');
}
}Type narrowing in templates
Angular’s template type checker can narrow a value inside an @if block or a matching @case. For example, checking a discriminated union can make a property available only where it is valid:
type Result =
| { kind: 'success'; value: string }
| { kind: 'failure'; message: string };Inside @if (result.kind === 'success'), Angular can treat result as the success shape. Inside the other branch, it can treat it as the failure shape. Keep related values in a discriminated union so the template checker can detect invalid property access.
Nesting and combining blocks
Blocks can contain other blocks. A common pattern is @if for permission or loading state, followed by @for for the available records. An @switch can then choose markup for each record’s state.
Keep each block focused. Deep nesting makes templates harder to read and test.
Common mistakes
- Omitting
@defaultwhen new union values may be added later. - Expecting fall-through between
@caseblocks. - Comparing values with the wrong type, such as a number with the string
'1'. - Using an unstable
trackexpression in a nested@for. Prefer a stable identifier such asitem.id. - Repeating an expensive expression instead of aliasing it with
@if (value; as result).
Migrating existing templates
@if replaces *ngIf, and @for replaces *ngFor. The track expression replaces trackBy. @switch replaces ngSwitch, ngSwitchCase, and ngSwitchDefault.
Angular can convert common usage automatically:
ng generate @angular/core:control-flowReview the result, especially track expressions and any ng-template references.
Exercise
Which branch renders when status is 'error', and why does Angular not render the following cases?
Show answer
The @case ('error') branch renders because its value strictly equals status. Angular renders only the first matching case and does not fall through.