The for directive in Angular
Let's say we have an array:
export class AppComponent {
public arr: string[] = ['a', 'b', 'c', 'd'];
}
Let's loop through this array in the template file. The *ngFor directive is designed for this. It can loop through the array and output each element in a separate tag.
First, this directive needs to be imported:
import {NgFor} from "@angular/common";
And add it to the imports section in the decorator:
@Component({
.....
imports: [....., NgFor],
....
})
Now we can use it. Let's see how it's done. Let's say we have a list ul:
<ul>
</ul>
Let's make it so that our array is looped through and each element is output in the li tags. This is done as follows:
<ul>
<li *ngFor="let el of arr">
{{ el }}
</li>
</ul>
Given an array:
export class AppComponent {
public arr: number[] = [1, 2, 3, 4, 5];
}
Print each element of this array in a separate paragraph.
Modify the previous task so that the squares of the elements of our array are output in paragraphs.