How to access the index in an Angular ngFor loop
Nick Scialli
August 20, 2022
In Angular, we can loop through an array using the ngFor
structural directive. In practice, we can envision an unordered todo list as follows:
<ul>
<li *ngFor="let todo of todos">{{ todo }}</li>
</ul>
And this will successfully output all your todos. But what if we want to add a number for each todo? For example, the first todo should display "Todo 1: Walk the dog"
.
In this case, we can add an index inside the directive:
<ul>
<li *ngFor="let todo of todos; let i = index">
Todo {{ i + 1 }}: {{ todo }}
</li>
</ul>
Of course, our loop is 0-indexed, so we add 1
to the index for a more human-readable version. We now have an index for each element of our array.
Happy coding!
Nick Scialli is a senior UI engineer at Microsoft.