For loop
Syntax
@for (item of items; track item.id) {
{{ item.name }}
}
track expression
- Allows Angular to maintain a relationship between your data and the DOM nodes on the page.
- Allows Angular to optimize performance by executing the minimum necessary DOM operations when the data changes.
- Using track effectively can significantly improve your application's rendering performance when looping over data collections.
- For static collections that never change, you can use
$index to tell Angular to track each item by its index in the collection.
Contextual variables in @for blocks
$count: Number of items in a collection
$index: Index of the current row
$first: Whether the current row is the first row
$last: Whether the current row is the last row
$even: Whether the current row index is even
$odd: Whether the current row index is odd
@for (item of items; track item.id; let idx = $index, e = $even) {
{{ item.name }}
}
Providing a fallback with the @empty block
- You can optionally include an
@empty section immediately after the @for block content. The content of the @empty block displays when there are no items:
@for (item of items; track item.name) {
<li> {{ item.name }}</li>
} @empty {
<li> There are no items. </li>
}