0 day streak
javascript / intermediate
Snippet

Multi-Branch State Rendering via Template Switch Blocks

Angular's built-in @switch control flow provides a declarative, type-checked syntax for branching template views without requiring structural directives like NgSwitch. It evaluates the expression once and renders only the matching @case branch or the fallback @default block.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import { Component, signal } from '@angular/core';
type OrderStatus = 'pending' | 'shipped' | 'delivered' | 'cancelled';
@Component({
selector: 'app-order-status',
standalone: true,
template: `
@switch (status()) {
@case ('pending') {
<span class="badge yellow">Order received, preparing shipment.</span>
}
@case ('shipped') {
<span class="badge blue">Package is in transit.</span>
}
@case ('delivered') {
<span class="badge green">Package delivered successfully.</span>
}
@default {
<span class="badge red">Order was cancelled or in unknown state.</span>
}
}
`
})
export class OrderStatusComponent {
status = signal<OrderStatus>('pending');
}
angular
Breakdown
1
@switch (status()) {
Begins the conditional switch block by reading the current value of the status signal.
2
@case ('shipped') {
Conditionally renders the inner template block only if status() strictly equals 'shipped'.
3
@default {
Acts as the fallback rendering branch when none of the specified case conditions are met.