Sub topic 9
Choosing between templates with @switch
This chapter covers the @switch block, which renders one of several templates based on the value of an expression. It assumes you know basic TypeScript, can write an Angular component with a template, and are comfortable with interpolation and event or property bindings. Familiarity with signals helps, because the examples use them. The @if and @else blocks from earlier chapters are the natural comparison point.
When @switch is the right tool
A chain of @else if blocks works when each branch tests a different condition. Many templates, though, compare a single value against several known options. A request state such as 'loading', 'error', or 'ready' is a typical case. Writing that as @if (status() === 'loading') ... @else if (status() === 'error') ... repeats the expression in every branch. @switch states the expression once and lists the possible values beneath it.
The block has three parts:
@switch (expression)holds the value to compare.@case (value)renders its content when the value matches.@defaultrenders its content when no case matches.
Basic syntax
The following component shows a different message for each state of a request.
import { Component, signal } from '@angular/core';
@Component({
selector: 'app-request-status',
template: `
@switch (status()) {
@case ('loading') {
<p>Loading...</p>
}
@case ('error') {
<p>Something went wrong.</p>
}
@default {
<p>Data is ready.</p>
}
}
`,
})
export class RequestStatusComponent {
status = signal<'loading' | 'error' | 'ready'>('loading');
}Angular evaluates status() once, then compares the result to each @case value in the order they appear. The first match renders and the rest are skipped. Because status is a signal, the block re-evaluates when the signal changes, and Angular swaps the rendered content for the new matching case.
Like the other built-in blocks, @switch needs no import. You do not add NgSwitch, NgSwitchCase, or CommonModule to the component's imports array.
How matching works
Three rules govern which case renders.
- Strict equality. Each
@caseis compared with the@switchexpression using===. The number1does not match the string'1', and an object only matches the same object reference. This is stricter than some people expect, and it is the same comparison the olderngSwitchdirective used. - No fall-through. Unlike a
switchstatement in JavaScript, there is nobreakand no fall-through. Only the first matching case renders. You cannot stack two@caseblocks to share a body. @defaultis a fallback. It renders only when no case matched. Its position in the block does not matter for matching, but placing it last reads most naturally.
The no-fall-through rule has a practical consequence. If two values should show the same content, you cannot write two empty cases followed by one with content. Instead, repeat the content, move it into a child component, or use @if with a combined condition for that part of the template.
import { Component, signal } from '@angular/core';
@Component({
selector: 'app-role-badge',
template: `
@switch (role()) {
@case ('admin') {
<span class="badge badge-strong">Staff</span>
}
@case ('editor') {
<span class="badge badge-strong">Staff</span>
}
@case ('viewer') {
<span class="badge">Guest</span>
}
@default {
<span class="badge">Unknown</span>
}
}
`,
})
export class RoleBadgeComponent {
role = signal<'admin' | 'editor' | 'viewer'>('admin');
}The repeated Staff badge is a small cost here. When the duplicated content grows, extract it into a component and reference it from both cases.
Diagram of the decision
The diagram below shows how Angular picks a branch.
Behavior when nothing matches
If no case matches and there is no @default, the block renders nothing. Angular does not report an error. This can hide bugs. If status later gains a new value such as 'empty' and you forget to add a case, the area of the page silently goes blank.
Including a @default block is a cheap safeguard. For values from a closed union type, you can make @default show an obvious fallback during development, so a missing case is visible.
Switching on more than strings
The @switch expression can be any template expression, and case values can be strings, numbers, booleans, null, or values read from the component, such as enum members.
Enums are a common source of friction. A template cannot reference an enum type directly, because only the component's members are in scope. Expose the enum as a property first.
import { Component, signal } from '@angular/core';
enum Plan {
Free,
Pro,
Team,
}
@Component({
selector: 'app-plan-label',
template: `
@switch (plan()) {
@case (Plan.Free) {
<p>Free plan: 3 projects</p>
}
@case (Plan.Pro) {
<p>Pro plan: unlimited projects</p>
}
@case (Plan.Team) {
<p>Team plan: unlimited projects and shared folders</p>
}
}
`,
})
export class PlanLabelComponent {
protected readonly Plan = Plan;
plan = signal<Plan>(Plan.Pro);
}The line protected readonly Plan = Plan; makes the enum visible to the template. Without it, the compiler reports that Plan does not exist on the component.
You can also switch on a boolean-producing expression with @switch (true), and use cases that evaluate comparisons. Because matching is strict, each case must produce exactly true to match, so a truthy value such as a non-empty string will not work.
import { Component, signal } from '@angular/core';
@Component({
selector: 'app-temperature',
template: `
@switch (true) {
@case (celsius() < 0) {
<p>Freezing</p>
}
@case (celsius() < 20) {
<p>Mild</p>
}
@default {
<p>Warm</p>
}
}
`,
})
export class TemperatureComponent {
celsius = signal(12);
}Cases are tested in order, so the freezing check comes first. A value of -5 satisfies both < 0 and < 20, but only the first match renders. For this kind of range logic, an @if / @else if chain usually reads more clearly, and it is the better choice when the conditions are not all comparisons against one value.
Combining @switch with other blocks
Case bodies can hold any template content, including other control flow blocks. A loading state might show a list with @for when data is ready.
import { Component, signal } from '@angular/core';
interface Task {
id: number;
title: string;
}
@Component({
selector: 'app-task-panel',
template: `
@switch (state()) {
@case ('loading') {
<p>Loading tasks...</p>
}
@case ('error') {
<p>Could not load tasks.</p>
<button (click)="state.set('loading')">Retry</button>
}
@case ('ready') {
<ul>
@for (task of tasks(); track task.id) {
<li>{{ task.title }}</li>
} @empty {
<li>No tasks yet.</li>
}
</ul>
}
}
`,
})
export class TaskPanelComponent {
state = signal<'loading' | 'error' | 'ready'>('ready');
tasks = signal<Task[]>([{ id: 1, title: 'Write spec' }]);
}Each case body has its own scope for content, and can contain several sibling elements without a wrapper. The error case above renders a paragraph and a button side by side, with no <ng-container> needed.
Type narrowing
The compiler checks each @case value against the type of the @switch expression. With a union type such as 'loading' | 'error' | 'ready', a case value like 'done' can never match, and strict template checking flags it. This catches typos at build time. Narrowing of the expression inside a case body is limited, so do not rely on @switch to narrow an object type the way @if narrows a nullable value. If you need the narrowed value, read it into an @if with an alias.
Differences from ngSwitch
The older directive form looked like this:
<div [ngSwitch]="status">
<p *ngSwitchCase="'loading'">Loading...</p>
<p *ngSwitchCase="'error'">Something went wrong.</p>
<p *ngSwitchDefault>Data is ready.</p>
</div>The built-in block differs in several ways:
| Aspect | `ngSwitch` | `@switch` |
|---|---|---|
| Imports | `NgSwitch`, `NgSwitchCase`, `NgSwitchDefault` or `CommonModule` | None |
| Host element | Requires an element that carries `[ngSwitch]` | No wrapper element |
| Case content | One element or `<ng-container>` per case | Any number of sibling nodes |
| Default | `*ngSwitchDefault` | `@default` |
| Matching | Strict equality | Strict equality |
The matching rules are the same, so a migrated template keeps its behavior. The block syntax removes the wrapper element and the extra imports.
Common mistakes
- Expecting fall-through. Two adjacent
@caseblocks do not share a body. Each needs its own content. - Forgetting the call on a signal.
@switch (status)compares the signal object itself, so no case matches. Write@switch (status()). - Mixing types. A numeric
1from a form value will not match@case ('1'). Convert the value or match its real type. - Omitting
@default. An unhandled value renders nothing, with no warning. - Using the enum without exposing it. Add a component property that points to the enum.
- Using truthy checks with
@switch (true). Each case must evaluate to the booleantrue, not just a truthy value.
Exercises
Exercise
A component has status = signal<'idle' | 'saving' | 'saved'>('idle'). The template contains @switch (status) { @case ('idle') { <p>Idle</p> } @case ('saving') { <p>Saving</p> } }. Nothing ever renders, even after the status is set to 'saving'. Name the two problems and fix them.
Show answer
First, status is a signal and must be called: @switch (status()). Without the call, the expression is the signal function itself, which never strictly equals a string. Second, there is no @case ('saved') and no @default, so the 'saved' state renders nothing. Add @case ('saved') { <p>Saved</p> } or a @default block.
Exercise
You want 'admin' and 'editor' to show the same panel, and 'viewer' to show a different one. Explain why two stacked @case blocks cannot share a body, and give two ways to avoid repeating a large panel.
Show answer
@switch has no fall-through, so each @case renders only its own content and an empty case renders nothing. To avoid repeating a large panel, move the panel into a child component and use it in both cases, or use an @if (role() === 'admin' || role() === 'editor') block with @else for the viewer panel.