0
0
AngularHow-ToBeginner · 3 min read

How to Use Index in ngFor in Angular

In Angular, you can access the current loop index in ngFor by using the syntax let i = index inside the directive. This index starts at 0 and lets you track the position of each item while looping through a list.
📐

Syntax

The ngFor directive lets you loop over a list. To get the current item's position, use let i = index inside the *ngFor tag. Here, i is a variable holding the zero-based index of the item.

  • let item of items: loops over each item
  • let i = index: captures the current index
html
<div *ngFor="let item of items; let i = index">
  {{i}} - {{item}}
</div>
💻

Example

This example shows a list of fruits with their indexes displayed before each name. It demonstrates how to use let i = index to show the position of each item in the list.

typescript + html
<!-- app.component.html -->
<ul>
  <li *ngFor="let fruit of fruits; let i = index">
    {{i + 1}}. {{fruit}}
  </li>
</ul>

<!-- app.component.ts -->
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent {
  fruits = ['Apple', 'Banana', 'Cherry', 'Date'];
}
Output
1. Apple 2. Banana 3. Cherry 4. Date
⚠️

Common Pitfalls

One common mistake is forgetting to declare the index variable with let, which causes an error. Another is assuming the index starts at 1, but it always starts at 0. Also, using the index to modify the original list can lead to bugs if not handled carefully.

html
<!-- Wrong: missing 'let' keyword -->
<div *ngFor="let item of items; i = index">
  {{i}} - {{item}}
</div>

<!-- Right: include 'let' keyword -->
<div *ngFor="let item of items; let i = index">
  {{i}} - {{item}}
</div>
📊

Quick Reference

UsageDescription
let i = indexDeclares a variable i with the current zero-based index
let first = firstTrue if the item is the first in the list
let last = lastTrue if the item is the last in the list
let even = evenTrue if the index is even
let odd = oddTrue if the index is odd

Key Takeaways

Use let i = index inside *ngFor to access the current item's zero-based index.
Always declare the index variable with let to avoid errors.
The index starts at 0, so add 1 if you want a human-friendly count.
Avoid using the index to change the original list directly to prevent bugs.
Angular also provides other context variables like first, last, even, and odd for more control.