Check out our Angular Book Series.

How do you access the index of an *ngFor look in Angular?

Sometimes in Angular I have to loop over something in an HTML template. *ngFor is the best way to do that. Something like this:


<div *ngFor="let myValue of myArray">
{{ myValue.property }}
</div>

This is pretty common. I've used it to create a list of items that do not warrant a data grid type structure. I've used it to populate drop downs or to display arrays of images. There are lots of uses for this.

Sometimes, I need to access the index of the array inside the loop. I was using this because I wanted to show which item was selected, and was switching some CSS based on the selected item. How do you access the index of the array inside the loop?

Like this:


<div *ngFor="let myValue of myArray; let i=index">
{{ myValue.property }}; {{index}}
</div>

It is really simple to do, but just does not come up all that often as this is the less common case.

You can even access a bunch more values inside the loop including determing whether the item is the first first and last item, or if it is is an even or odd element. All these allow you to easily make tweaks to the display.

Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
All Content Copyright 2005, 2006, 2007, 2008, 2009 Jeffry Houser. May not be reused without permission
BlogCFC was created by Raymond Camden. This blog is running version 5.9.2.002.