The for directive in Angular

Let's say we have an array:

app/app.component.tsexport 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:

app/app.component.tsimport {NgFor} from "@angular/common";

And add it to the imports section in the decorator:

app/app.component.ts@Component({
  .....
  imports: [....., NgFor],
  ....
})

Now we can use it. Let's see how it's done. Let's say we have a list ul:

app/app.component.html<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:

app/app.component.html<ul>
  <li *ngFor="let el of arr">
    {{ el }}
  </li>
</ul>
Задание 1

Given an array:

app/app.component.tsexport class AppComponent {
  public arr: number[] = [1, 2, 3, 4, 5];
}

Print each element of this array in a separate paragraph.

Задание 2

Modify the previous task so that the squares of the elements of our array are output in paragraphs.