|
1 |
| -Placeholder content |
| 1 | +The `@for` block repeatedly renders content of a block for each item in a collection. |
| 2 | + |
| 3 | +@syntax |
| 4 | + |
| 5 | +```html |
| 6 | +@for (item of items; track item.name) { |
| 7 | + <li> {{ item.name }} </li> |
| 8 | +} @empty { |
| 9 | + <li> There are no items. </li> |
| 10 | +} |
| 11 | +``` |
| 12 | + |
| 13 | +@description |
| 14 | + |
| 15 | +The `@for` block renders its content in response to changes in a collection. Collections can be any JavaScript [iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols), but there are performance advantages of using a regular `Array`. |
| 16 | + |
| 17 | +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. |
| 18 | + |
| 19 | +<h3> track and objects identity </h3> |
| 20 | + |
| 21 | +The value of the `track` expression determines a key used to associate array items with the views in the DOM. Having clear indication of the item identity allows Angular to execute a minimal set of DOM operations as items are added, removed or moved in a collection. |
| 22 | + |
| 23 | +Loops over immutable data without `trackBy` as one of the most common causes for performance issues across Angular applications. Because of the potential for poor performance, the `track` expression is required for the `@for` loops. When in doubt, using `track $index` is a good default. |
| 24 | + |
| 25 | +<h3> `$index` and other contextual variables </h3> |
| 26 | + |
| 27 | +Inside `@for` contents, several implicit variables are always available: |
| 28 | + |
| 29 | +| Variable | Meaning | |
| 30 | +| -------- | ------- | |
| 31 | +| `$count` | Number of items in a collection iterated over | |
| 32 | +| `$index` | Index of the current row | |
| 33 | +| `$first` | Whether the current row is the first row | |
| 34 | +| `$last` | Whether the current row is the last row | |
| 35 | +| `$even` | Whether the current row index is even | |
| 36 | +| `$odd` | Whether the current row index is odd | |
| 37 | + |
| 38 | +These variables are always available with these names, but can be aliased via a `let` segment: |
| 39 | + |
| 40 | +```html |
| 41 | +@for (item of items; track item.id; let idx = $index, e = $even) { |
| 42 | + Item #{{ idx }}: {{ item.name }} |
| 43 | +} |
| 44 | +``` |
| 45 | + |
| 46 | +The aliasing is especially useful in case of using nested `@for` blocks where contextual variable names could collide. |
0 commit comments