如何在html Angular 17中使用@for中的索引

Ali*_*adi 1 html typescript angular angular17

如何在Angular 17中定义index变量@for

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>
Run Code Online (Sandbox Code Playgroud)

索引并不为我们所知,因为我们已经输入*ngFor并得到了Unknown "let" parameter variable "index" in Angular17 @for

但以下内容有效:

<ul>
  <li *ngFor="let user of users; let i = index">{{ user.name + i }}</li>
</ul>
Run Code Online (Sandbox Code Playgroud)

Mat*_*ler 5

您可以在块$index范围内的任何地方使用@for,而无需为其添加别名:

<ul>
  @for (user of users; track user.id) {
     <li>{{ user.name + $index }}</li>
  } @empty {
     <span>Empty list of users</span>
  }
</ul>
Run Code Online (Sandbox Code Playgroud)