How to use index in @for in html angular 17
Asked Answered
E

3

10

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:

<ul>
  <li *ngFor="let user of users; let i = index">{{ user.name + i }}</li>
</ul>
Eisenhart answered 16/2 at 15:6 Comment(0)
E
8

Just $ was missing, it should be $index rather than index. Also there are some other contextual variables rather than $index REF:

Variable Meaning
$count Number of items in a collection iterated over
$index Index of the current row
$first Whether the current row is the first row
$last Whether the current row is the last row
$even Whether the current row index is even
$odd Whether the current row index is odd

and the usage would be:

@for (item of items; track item.id; let idx = $index, e = $even) {
  Item #{{ idx }}: {{ item.name }}
}

We can also utilize our existing template and execute this command to migrate to control-flow.

ng g @angular/core:control-flow
Eisenhart answered 16/2 at 17:36 Comment(0)
P
11

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>
Phobe answered 16/2 at 15:8 Comment(1)
u need to alias it sometimes if u have a nested forMartres
E
8

Just $ was missing, it should be $index rather than index. Also there are some other contextual variables rather than $index REF:

Variable Meaning
$count Number of items in a collection iterated over
$index Index of the current row
$first Whether the current row is the first row
$last Whether the current row is the last row
$even Whether the current row index is even
$odd Whether the current row index is odd

and the usage would be:

@for (item of items; track item.id; let idx = $index, e = $even) {
  Item #{{ idx }}: {{ item.name }}
}

We can also utilize our existing template and execute this command to migrate to control-flow.

ng g @angular/core:control-flow
Eisenhart answered 16/2 at 17:36 Comment(0)
T
3

You can also write it like this:

<ul>
  @for (user of users; track user.id; let idx = $index) {
     <li>{{ user.name + idx }}</li>
  } @empty {
     <span>Empty list of users</span>
  }
</ul>
Tatro answered 16/2 at 17:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.