@for is Angular’s built-in template syntax for repeating content from an iterable. It replaces NgFor with explicit tracking, optional empty-state rendering, and contextual variables for indexes, counts, and item position. section 10.1.2 section 10.5
Use the block to make repeated UI explicit and informative:
- Track each item with a meaningful property such as notification.id. section 10.1.2 section 10.1.4
- Attach an @empty block when an empty iterable needs its own UI. section 10.1.2
- Use $index, $count, $first, $last, $even, and $odd directly, or alias them locally for nested loops. section 10.1.2
HRMS notifications
A notification dialog can iterate over notifications(), track notification.id, show each title and message, offer a read-state action, display “No notifications to display” when empty, and render a counter such as 2/17 with $index and $count. section 10.1.2
Listing 10.4 @for loops in Angular templates
@Component({
selector: 'app-header',
template: `
<header>
<h2>HRMS</h2>
<button (click)="notificationsOpen.set(true)" title="View Notifications">
You have {{ unreadNotifications.length }} unread notifications
</button>
</header>
<dialog [open]="notificationsOpen()">
<h3>Notifications</h3>
<ul>
@for (
notification of notifications();
track notification.id
) { #1
<li>
<h4>{{ notification.title }}</h4>
<span>{{ notification.message }}</span>
@if (!notification.read) {
<button (click)="markNotificationAsRead(notification)">
Mark as Read
</button>
} @else {
<span title="Notification is read">✔</span>
}
</li>
}
</ul>
<button (click)="notificationsOpen.set(false)">Close</button>
</dialog>
`,
standalone: true,
#2
})
export class HeaderComponent {
#3
}
Inspect a complete @for template combining tracking, nested @if state handling, notification actions, and interpolated values. section 10.1.2
Migration can proceed incrementally with Angular’s control-flow schematic. Review generated tracking expressions, remove obsolete directive imports manually, and run regression tests because automated conversion may require cleanup. section 10.1.4
