Working with the current index in Angular ngFor
Angular ngFor directive helps us loop over an item and interpolate it in our template file. Most of the time we might also be interested to get the current index in Angular ngFor. Furthermore, we might be interested in whether the items are located on the even or odd index. Angular provides an easy way to accomplish this. Here is an example:-
Getting the current index in Angular
<div *ngFor="let item of items; let i = index;"></div>
The simple additional statement
let i = index; will enable us to use
i as the current index in Angular ngFor. Similarly, we can use the even and odd variable in the loop scope like this.
<div *ngFor="let item of items; let i = index; let e = even; let o = odd"></div>
Alternatively, we can use this syntax:-
<div *ngFor="let item of items; index as i; even as e; odd as o"></div>
What this means is, inside our div, we can use the variables,
o to work with the current item’s index, and to see whether this item is at an even or odd place. Hence, we can maybe apply CSS to the rows of items.
*ngFor is a shorthand directive, it is expanded into a longer HTML with template tag in it, take a look at the documentation from Angular. Plus, the technical documentation reveals a number of other variables including
last which helps in working with the first element, and last element, of the loop.
Getting the total items in Angular
*ngFor directive provides the
count variable to help us display the total items in our list. Similar to the above syntax, we can work with it like this.
<div *ngFor="let item of items; count as total"></div>
We can use interpolation to display the total at the top of our list.
How to generate an
*ngFor loop from a number
In most programming languages it is possible to loop from zero to a number. There is no direct way to accomplish this in Angular *ngFor. However, we can simply construct an array and iterate through it like this.
<div *ngFor="let item of .constructor(n)"></div>
In the above code, we are building an empty array of size n.