TypeOfNaN

How to access the index in an Angular ngFor loop

Nick Scialli
August 20, 2022

New โ€” Check out my free newsletter on how the web works!

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!

๐ŸŽ“ Learn how the web works

One of the best ways to level up your tech career is to have a great foundational understanding of how the web works. In my free newsletter, How the Web Works, I provide simple, bite-sized explanations for various web topics that can help you boost your knowledge. Join 2,500+ other learners on the newsletter today!

Signing up is free, I never spam, and you can unsubscribe any time. You won't regret it!

Sign up for the newsletter ยป
Nick Scialli

Nick Scialli is a senior UI engineer at Microsoft.

ยฉ 2024 Nick Scialli