Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use index in @for in html angular 17

How can I define the index variable in @for in Angular 17

const users = [
    { id: 1, name: 'Ali' },
    { id: 2, name: 'reza' },
    { id: 3, name: 'jack' },
  ];

<ul>
  @for (user of users; track user.id; let i = index) {
  <li>{{ user.name + i }}</li>
  } @empty {
  <span>Empty list of users</span>
  }
</ul>

index is not known as we had in *ngFor and got Unknown "let" parameter variable "index" in Angular17 @for

But the following is working:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<ul>
  <li *ngFor="let user of users; let i = index">{{ user.name + i }}</li>
</ul>

>Solution :

You can use $index everywhere in the scope of the @for block without having to alias it:

<ul>
  @for (user of users; track user.id) {
     <li>{{ user.name + $index }}</li>
  } @empty {
     <span>Empty list of users</span>
  }
</ul>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading