0 day streak
javascript / intermediate
Snippet

Iterating Collections with Empty State Handling Using Template For Blocks

The built-in @for control flow block provides a declarative way to iterate over iterable data structures while tracking item identity. Its optional @empty block automatically renders fallback markup whenever the collection contains zero elements.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import { Component } from '@angular/core';
@Component({
selector: 'app-user-list',
standalone: true,
template: `
<ul>
@for (user of users; track user.id; let idx = $index, total = $count) {
<li>{{ idx + 1 }} / {{ total }}: {{ user.name }}</li>
} @empty {
<li class="empty-message">No active users found in the system.</li>
}
</ul>
`
})
export class UserListComponent {
users = [{ id: 101, name: 'Alice' }, { id: 102, name: 'Bob' }];
}
angular
Breakdown
1
@for (user of users; track user.id; let idx = $index, total = $count) {
Iterates over the users array, tracks elements by their unique id, and exposes index and count context variables.
2
<li>{{ idx + 1 }} / {{ total }}: {{ user.name }}</li>
Interpolates the 1-based index, total element count, and item name into list elements.
3
} @empty {
Defines an alternative template section triggered when the underlying iterable is empty.
4
<li class="empty-message">No active users found in the system.</li>
Displays a user-friendly placeholder message when no items exist.