Write Angular like a pro. Angular Icon

Follow the ultimate Angular roadmap.

Accessing the index inside NgFor

In this post you’re going to learn how to get the index with ngFor in Angular.

The way to access the index with NgFor is through what’s called a local variable. Each iteration inside the NgFor “loop” exposes to us a set of local variables - index, count, first, last, even, odd.

You can see all other variables exposed to us in the NgForOf documentation.

Here’s what a basic NgFor directive looks like:

<todo-item
  *ngFor="let todo of todos"
  [todo]="todo">
</todo-item>

But let’s say we want to access the index, just like we could inside a typical Array.prototype.forEach, we can use the following syntax to expose the index variable:

<todo-item
  *ngFor="let todo of todos; index as i"
  [todo]="todo"
  [index]="i">
</todo-item>

By declaring index as i we make the index value available to us under a variable called i, which is a common practice with Angular’s ngFor.

From here, we can then use {{ i }} inside the template to log out the value for each item in the loop.

For more advanced cases, you’ll want to think about using the <ng-template> syntax which expands the NgFor directive to include NgForOf, here’s how we do that:

<ng-template ngFor let-todo [ngForOf]="todos" let-i="index">
  <todo-item 
    [todo]="todo"
    [index]="i">
  </todo-item>
</ng-template>

Notice let-i and let-todo are both declaring the variables we’d like to access (to pass into [todo] and [index]). We then specify to [ngForOf] that we’d like to iterate the todos array. You can see now how ngFor works behind the scenes.

Summary

So, that’s how to access the current array index with the Angular NgFor directive. It’s helpful to uncover things like this, especially given the previous ways to access the index and how syntax has changed over the years - but this is the most up-to-date way of doing things.

Use the typical *ngFor style alongside index as i and you’re good to go. For the more advanced templating cases, use the <ng-template> syntax with NgFor and access your let-i="index" variable (however it doesn’t really explain the index as i syntax for the *ngFor style and the let-i approach for the expanded syntax).

🏆 Check out my brand new Angular v15 course where you’ll learn Angular, TypeScript, RxJS and state management principles from beginning to expert level.

Angular’s ngFor not only exposes the index, but many other useful properties that can be used in combination for more advanced use cases.

Learn Angular the right way.

The most complete guide to learning Angular ever built.
Trusted by 82,951 students.

Todd Motto

with Todd Motto

Google Developer Expert icon Google Developer Expert

Related blogs 🚀

Free eBooks:

Angular Directives In-Depth eBook Cover

JavaScript Array Methods eBook Cover

NestJS Build a RESTful CRUD API eBook Cover