Welcome back Angular devs! 👋
In Part 1 and Part 2, we explored the powerful @if
and @for
blocks in Angular 20’s new control flow system.
Now, let’s complete the trio with the newly introduced @switch
directive — a clean and readable way to handle multiple conditional views.
🔀 What is @switch
?
The @switch
block allows Angular templates to conditionally render one of several possible blocks, based on the result of a single expression — just like JavaScript’s switch
statement.
🔧 Syntax
@switch (expression) {
@case (value1) {
<!-- Template for case value1 -->
}
@case (value2) {
<!-- Template for case value2 -->
}
@default {
<!-- Fallback template if no case matches -->
}
}
🧪 Example: Status Viewer
Let’s build a simple component that shows the status of a request and lets users update it with the click of a button.
<div class="status">
@switch (status()) {
@case ('Init') {
<span>Request Init</span>
}
@case ('Loading') {
<span>Request In Progress</span>
}
@case ('Completed') {
<span>Request Completed</span>
}
@default {
<span>Status not available</span>
}
}
</div>
<div class="btn-container">
<button type="button" (click)="requestChange('Init')">Init Request</button>
<button type="button" (click)="requestChange('Loading')">Request In Progress</button>
<button type="button" (click)="requestChange('Completed')">Request Completed</button>
</div>
🎯 Component Code
import { Component, signal } from '@angular/core';
@Component({
selector: 'app-status',
templateUrl: './status.html',
styleUrl: './status.scss'
})
export class StatusComponent {
status = signal<'Init'| 'Loading' | 'Completed'| ''>(''); // Starts as empty
requestChange(value: string) {
this.status.set(value);
}
}
Output:
On component load, the default message is shown (Status not available
).
Clicking a button updates the status dynamically, and the matching case content is rendered — all without cluttering your component with conditionals.
📌 Notes:
-
@switch
compares using strict equality (===
). -
@default
is optional. - There’s no fallthrough like in JS. Each case is isolated — so no need for
break
orreturn
.
✅ Summary of @switch
Feature | Behavior |
---|---|
Strict Compare | Uses === to match values |
No Fallthrough | Each @case is isolated |
Optional Default |
@default is a fallback but not mandatory |
Clean Syntax | Clear, nested, and familiar structure |
🧵 Final Words
With @if
, @for
, and now @switch
, Angular 20 templates just got a huge upgrade in readability, reactivity, and structure.
Missed previous parts?
➡️ Part 1: @if
➡️ Part 2: @for
✍️ Author: Vetriselvan
👨💻 Frontend Developer | Code Lover | Exploring Angular’s future