How to get index of ngFor element in Angular

To get the index of an element in an *ngFor loop in Angular, you can use the index directive. Here is an example of how you can use it:

<ul>
  <li *ngFor="let item of items; index as i">
    {{i}} - {{item}}
  </li>
</ul>

This will display a list of items, with the index of each item displayed before the item itself.

You can also use the index directive to get the index of an element in an *ngFor loop inside a component class. Here is an example of how you can do this:

<ul>
  <li *ngFor="let item of items; index as i" (click)="onClick(i)">
    {{item}}
  </li>
</ul>
export class MyComponent {
  items = ['Item 1', 'Item 2', 'Item 3'];

  onClick(index: number) {
    console.log(`Clicked item at index ${index}`);
  }
}

In this example, when the user clicks on an item in the list, the onClick method will be called with the index of the clicked item passed as an argument.

You can also use the first, last, and even/odd directives to get information about the first, last, and even/odd elements in an *ngFor loop. Here is an example of how you can use these directives:

<ul>
  <li *ngFor="let item of items; index as i; first as isFirst; last as isLast; even as isEven; odd as isOdd">
    {{i}} - {{item}} - First: {{isFirst}}, Last: {{isLast}}, Even: {{isEven}}, Odd: {{isOdd}}
  </li>
</ul>

This will display a list of items, with the index, first/last/even/odd status of each item displayed after the item itself.

I hope this helps! Let me know if you have any questions.

Facebook
Twitter
LinkedIn
Pinterest

Related posts

AngularJS Directives

In the landscape of JavaScript frameworks, AngularJS stands out for its feature-rich nature and comprehensive solution for building web applications.

Read More