How to access the index in an Angular ngFor loop

Nick Scialli August 20, 2022🚀 1 minute read

In Angular, we can loop through an array using the ngFor structural directive. In practice, we can envision an unordered todo list as follows:

  <li *ngFor="let todo of todos">{{ todo }}</li>

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:

  <li *ngFor="let todo of todos; let i = index">
    Todo {{ i + 1 }}: {{ todo }}

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!

Did this post help you?

I'd appreciate your feedback so I can make my blog posts more helpful. Did this post help you learn something or fix an issue you were having?

If you'd like to support this blog by buying me a coffee I'd really appreciate it!

Nick Scialli

Nick Scialli is a senior UI engineer at the Microsoft.