0 day streak
javascript / intermediate
Snippet

Template Iteration Tracking on Dynamic Collections

Angular built-in control flow `@for` provides optimized DOM recycling over array collections. Specifying the `track` expression avoids re-rendering unaffected DOM nodes when items are modified or reordered.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
@if (userRoles().length > 0) {
<ul class="role-list">
@for (role of userRoles(); track role.id; let idx = $index, isFirst = $first) {
<li [class.primary-badge]="isFirst">
<span>#{{ idx + 1 }}: {{ role.name }}</span>
<button (click)="removeRoleAtIndex(idx)">Remove</button>
</li>
} @empty {
<li class="empty-notice">No active roles assigned.</li>
}
</ul>
}
angular
Breakdown
1
@for (role of userRoles(); track role.id; let idx = $index, isFirst = $first) {
Iterates through the array signal items while tracking identity via unique id and aliasing index variables.
2
<li [class.primary-badge]="isFirst">
Conditionally binds a CSS class using the loop iteration contextual boolean variable.
3
} @empty {
Renders a fallback template node directly when the source array contains zero elements.