Sub topic 9
Choosing between templates with @switch
This chapter assumes you know TypeScript, Angular components and templates, property and event binding, and have seen signals. It covers @switch, which picks one of several templates by comparing a value against fixed cases.
When to use @switch
@if with @else if chains works for conditions of any shape. When every branch compares one expression against a specific value, a @switch block is easier to read. It names the expression once and lists the possible values below it.
@switch replaces the ngSwitch, *ngSwitchCase, and *ngSwitchDefault directives. It is built into the template compiler, so you do not import a module or directive to use it.
Basic syntax
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');
}The parts work as follows:
@switch (expression)evaluates the expression whenever it changes.- Each
@case (value)holds the content to render when the expression matches that value. @defaultholds the content to render when no case matches. It is optional.
The status signal is read with status(), so the block updates when the signal changes. Setting it to 'error' removes the loading paragraph and renders the error paragraph.
How matching works
The @switch block follows three rules.
- Strict equality. The expression is compared to each case with
===. The string'1'does not match the number1. - First match wins. Angular checks cases from top to bottom and renders only the first one that matches.
- No fall-through. Unlike a
switchstatement in JavaScript, you do not writebreak. Only the matching case renders, and nothing after it runs.
If nothing matches and there is no @default, the block renders nothing.
Cases can use expressions
A @case value is not limited to a literal. It can be any template expression, such as a property of the component. This lets you compare against a constant or an enum.
import { Component, signal } from '@angular/core';
enum Role {
Admin,
Editor,
Viewer,
}
@Component({
selector: 'app-role-badge',
template: `
@switch (role()) {
@case (Roles.Admin) {
<span>Administrator</span>
}
@case (Roles.Editor) {
<span>Editor</span>
}
@default {
<span>Viewer</span>
}
}
`,
})
export class RoleBadgeComponent {
protected readonly Roles = Role;
role = signal<Role>(Role.Viewer);
}Templates cannot see a module-level enum directly. The class exposes it through the Roles property, and protected is enough because templates can read protected members.
Matching several values
Each @case takes one value. Because there is no fall-through, you cannot stack cases the way you can in JavaScript. For several values that share a template, you have three options:
- Use
@ifwith a combined condition, such as@if (status() === 'error' || status() === 'timeout'). - Compute a simpler value in the class, for example a
computedsignal that maps many statuses to one category, and switch on that. - Repeat the content, or move it into a small child component that each case uses.
Common mistakes
- Type mismatches. Comparing a number signal to a string case never matches, because of strict equality.
- Condition-style cases. Writing
@case (count() > 5)comparescount()totrueorfalse, not to the result you probably want. For range checks, use@ifand@else if. - Forgetting
@default. With a value that can be anything, such as a string from an API, add a@defaultso unknown values still show something.
Before and after
The older form needed the ngSwitch directives on an element, which also created a wrapper element when you wanted a single one.
<!-- Before -->
<div [ngSwitch]="status">
<p *ngSwitchCase="'loading'">Loading...</p>
<p *ngSwitchCase="'error'">Something went wrong.</p>
<p *ngSwitchDefault>Data is ready.</p>
</div>
<!-- After -->
@switch (status) {
@case ('loading') { <p>Loading...</p> }
@case ('error') { <p>Something went wrong.</p> }
@default { <p>Data is ready.</p> }
}The new form needs no host element and no NgSwitch imports.
Exercise
A component has count = signal(1). A template contains @switch (count()) { @case ('1') { <p>One</p> } @default { <p>Other</p> } }. What renders, and why?
Show answer
It renders "Other". The @case compares with strict equality, and the number 1 is not strictly equal to the string '1', so the case does not match and @default renders. Changing the case to @case (1) makes it render "One".
Exercise
You want the same message for the statuses 'error' and 'timeout' and a different message for 'ready'. Since @case cannot be stacked, name one way to do this.
Show answer
Use @if (status() === 'error' || status() === 'timeout') { ... } @else if (status() === 'ready') { ... }. Alternatively, create a computed signal that maps both statuses to one category such as 'failed', and switch on that value.