1

How to access the index in an Angular ngFor loop

 2 years ago
source link: https://typeofnan.dev/how-to-access-index-in-angular-ngfor-loop/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

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:

<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!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK