0%

angular-directive-ngfor

Introduction

NgFor is a structural directive in Angular, it is used to iterate over a list of items and render them in the template.

Usage

Suppose you have a months array in your component which contains ‘January’, ‘February’, ‘March’, and You want to render them in the template, you can use NgFor directive to achieve this.

1
2
3
4
5
6
7
8
9
10
11
// app.component.ts
@Component({
selector: 'app-ng-for',
templateUrl: './ng-for.component.html',
styleUrls: ['./ng-for.component.less']
})
export class NgForComponent implements OnInit {
months: string[] = ['January', 'February', 'March'];
constructor() {}
ngOnInit(): void {}
}
1
2
3
4
5
6
<!--app.component.html-->
<div class="months">
<ul *ngFor="let month of months">
<li>{{month}}</li>
</ul>
</div>

Note that, *ngFor start iteration from the element where it is placed, in this case, it starts from the ul element and renders as below:

1
2
3
4
5
6
7
8
9
10
11
<div class="months">
<ul>
<li>January</li>
</ul>
<ul>
<li>February</li>
</ul>
<ul>
<li>March</li>
</ul>
</div>

In order to render the list in a single ul element, you can place *ngFor on the li element:

1
2
3
4
5
6
<!--app.component.html-->
<div class="months">
<ul>
<li *ngFor="let month of months">{{month}}</li>
</ul>
</div>

track index

If you want to track the index of the current item, you can use index, note index is zero-based.

1
2
3
4
5
6
<!--app.component.html-->
<div class="months">
<ul>
<li *ngFor="let month of months; let i = index">{{i + 1}}. {{month}}</li>
</ul>
</div>

The code above will render as below:

1
2
3
4
5
6
7
<div class="months">
<ul>
<li>1. January</li>
<li>2. February</li>
<li>3. March</li>
</ul>
</div>

Use @for

With the new built-in structural @for directive, you can use the following syntax:

1
2
3
4
5
<ul>
@for(month of months; track $index) {
<li>{{$index + 1}}. {{ month }}</li>
}
</ul>

Reference

  1. https://angular.dev/api/core/@for#