0 day streak
javascript / intermediate
Snippet

Evaluating Complex Branching with Built-in Switch Control Flow

Angular's native control flow syntax provides declarative, type-checked branching blocks directly within component templates. The @switch block evaluates an expression and conditionally renders the matching @case block with zero runtime overhead compared to legacy structural directives like *ngSwitchCase.

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, input } from '@angular/core';
export type UserStatus = 'pending' | 'active' | 'suspended' | 'archived';
@Component({
selector: 'app-status-badge',
standalone: true,
template: `
@switch (status()) {
@case ('active') {
<span class="badge badge-success">Account Active</span>
}
@case ('pending') {
<span class="badge badge-warning">Verification Required</span>
}
@case ('suspended') {
<span class="badge badge-danger">Account Locked</span>
}
@default {
<span class="badge badge-neutral">Status Unknown</span>
}
}
`
})
export class StatusBadgeComponent {
readonly status = input.required<UserStatus>();
}
angular
Breakdown
1
readonly status = input.required<UserStatus>();
Defines a strongly typed required signal input accepting members of the UserStatus union type.
2
@switch (status()) {
Initiates built-in template branching by evaluating the current value of the status signal.
3
@case ('active') { <span class="badge badge-success">Account Active</span> }
Renders DOM nodes specific to the 'active' state when matched against the evaluated expression.
4
@default { <span class="badge badge-neutral">Status Unknown</span> }
Defines a fallback template block rendered when none of the specified case conditions are met.