在 ngFor 中获取当前索引

当我们将数据存储在数组(员工列表)中时,我们可以使用 *ngFor 函数将此数据转换为网页上的表格格式。

当我们在 *ngFor 中进行索引时,它可以帮助我们对数组中的项目列表进行编号,从而更容易跟踪列表中的项目,尤其是在处理大量列出的项目时。

例如,我们正在处理一个课程列表,因此在 app.component.ts 中,我们将在一个数组中创建该列表并将其命名为 courses

我们应该注意我们给数组的名称,因为我们将使用 *ngFor 来获取索引,使用 i-variable

app.component.ts 中,我们将输入以下内容:

import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
courses = [
{ id:1, name:'course1' },
{ id:2, name:'course2' },
{ id:3, name:'course3' }
];
}

当你查看数组时,你会看到它被命名为 courses,正如我们最初解释的那样。

接下来是进入 app.component.html 以传入 *ngFor 函数,该函数将负责让数组被索引。

在这里,我们将传递一些指令:

<ul>
  <li *ngFor="let course of courses; index as i">
      {{ i }} - {{ course.name }}
  </li>
</ul>

输出示例链接