0 day streak
javascript / intermediate
Snippet

Template Control Flow with Type-Safe Let Declarations and Empty Fallback

Angular's modern built-in control flow (@switch, @for, @let) integrates directly with TypeScript's discriminated unions. The @let block captures the evaluated signal value once, enabling narrowing across branches. The @for block provides explicit identity tracking via 'track' and includes a declarative @empty block when collections have zero items.

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
28
29
30
31
32
33
34
35
import { Component, input } from '@angular/core';
export type LoadingState<T> =
| { status: 'idle' }
| { status: 'loading' }
| { status: 'success'; data: readonly T[] }
| { status: 'error'; message: string };
@Component({
selector: 'app-item-list',
standalone: true,
template: `
@let state = stateInput();
@switch (state.status) {
@case ('loading') {
<div class="spinner">Loading records...</div>
}
@case ('success') {
<ul>
@for (item of state.data; track item.id; let idx = $index) {
<li>{{ idx + 1 }}. {{ item.name }}</li>
} @empty {
<li class="empty-hint">No items found in dataset.</li>
}
</ul>
}
@case ('error') {
<p class="error-text">{{ state.message }}</p>
}
}
`
})
export class ItemListComponent {
readonly stateInput = input.required<LoadingState<{ id: string; name: string }>>();
}
angular
Breakdown
1
export type LoadingState<T> =
Defines a generic discriminated union representing distinct asynchronous lifecycle states.
2
@let state = stateInput();
Stores the signal output in a local template variable to avoid repeated evaluations and enable type narrowing.
3
} @empty {
Renders a declarative fallback template automatically when the iterated array is empty without extra *ngIf conditions.