How to Get the index of ngFor in Angular?

Just like a normal for loop, an *ngFor directive can also have an index to keep track of the item that is currently being processed. This index value you can either directly use in your template file or you can even send it to your ts file to get the information of the current item.

In Angular, there are two approaches that you can use to get the index of ngFor:

Let me show you both approaches with examples.


1. Using the let keyword

In this approach, you have to first declare a variable using the let keyword inside the *ngFor loop and then simply assign it with the index. For instance, let i = index.

Here i is the variable that we have defined. You can name it whatever you want such as counter, elementIndex, etc.

See this example:

<div *ngFor="let item of items; let i = index">
    <p>The index of {{item}} is: {{i}}</p>
</div>

And here is the output we got:

The index of Apple is: 0

The index of Banana is: 1

The index of Grapes is: 2

The index of Mango is: 3

Get index value in ts file:

The index value of the current item being iterated can also be passed to the ts file. This generally helps us in situations where we need to get the index of the current item that is clicked.

To do this, you need two things. First, pass the index as a function parameter which triggers on the click event.

In the following example, we have passed the index i to the function getIndex(i) which is triggered on clicking a paragraph.

<div *ngFor="let item of items; let i = index">
    <p (click)="getIndex(i)">The index of  {{item}} is: {{i}}</p>
</div>

Now, you need to define the function getIndex() in your ts file to get the current index value:

getIndex(indxVal){
    console.log(indxVal);
}

2. Using the as keyword

The second approach to get the index of ngFor is to use the as keyword. This is also very similar to the approach that we have discussed above.

The only difference is that we use the keyword as instead of let to declare the variable. For instance, index as i.

See the implementation below:

<div *ngFor="let item of items; index as i;">
    <p>The index of {{item}} is: {{i}}</p>
</div>

This also gives us the same output as above:

The index of Apple is: 0

The index of Banana is: 1

The index of Grapes is: 2

The index of Mango is: 3

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.