The for construct in Angular
You can also loop through array elements using the @for construct.
Let's try it in practice. Let's say there is an array in our component again:
export class AppComponent {
public arr: number[] = [1, 2, 3, 4, 5];
}
Let's look at the syntax of the construction:
@for () {
tags
}
Let's specify the array to be iterated over and the variable into which the elements will be placed:
@for (elem of arr) {
tags
}
However, that's not all. For Angular to work correctly, we must specify a special command track. After it, we must specify some unique value for each array element. This is necessary so that Angular can work with the DOM more optimally. Let's take the array element number as such a unique value. To do this, we must specify the variable $index. So, here is our final code:
@for (elem of arr; track $index) {
<div>
{{ elem }}
</div>
}
Given an array:
export class AppComponent {
public arr: numbers[] = [1, 2, 3, 4, 5];
}
Print each element of this array in a separate paragraph.