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 | // app.component.ts |
1 | <!--app.component.html--> |
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 | <div class="months"> |
In order to render the list in a single ul
element, you can place *ngFor
on the li
element:
1 | <!--app.component.html--> |
track index
If you want to track the index of the current item, you can use index
, note index
is zero-based.
1 | <!--app.component.html--> |
The code above will render as below:
1 | <div class="months"> |
Use @for
With the new built-in structural @for
directive, you can use the following syntax:
1 | <ul> |