Angular ngFor 没有可迭代对象。需要构建 Iterable

Angular ngFor without an iterable. Need to Build the Iterable

在 Angular 中有一个 *ngFor 2+ 需要通过创建 n 个元素的数组来构建可迭代(行):

<table>
  <tr *ngFor="let row of rows">

  </tr>
</table>

有没有一种迭代数字的方法??。 提前致谢。

我将使用此语法将索引值设置为 HTML 元素的属性:

<table>
  <tr *ngFor="let item of items; let i = index" [attr.data-index]="i"> // data-index attribute will be assigned index 

  </tr>
</table>

您可以使用组件的方法生成行索引数组 class:

public generateRowIndexes(count: number): Array<number> {
  let indexes = [];
  for (let i = 0; i < count; i++) {
    this.indexes.push(i);
  }
  return indexes;
}

并在模板中调用它:

<table>
  <tr *ngFor="let rowIndex of generateRowIndexes(5)">
    ...
  </tr>
</table>

代码可以在this stackblitz中测试。