Angular 2:如何编写 for 循环,而不是 foreach 循环

问题描述:

使用 Angular 2,我想多次复制模板中的一行.迭代一个对象很容易,*ngFor="let object of objects".但是,我想运行一个简单的 for 循环,而不是一个 foreach 循环.类似(伪代码):

Using Angular 2, I want to duplicate a line in a template multiple times. Iterating over an object is easy, *ngFor="let object of objects". However, I want to run a simple for loop, not a foreach loop. Something like (pseudo-code):

{for i = 0; i < 5; i++}
  <li>Something</li>
{endfor}

我该怎么做?

如果将 int 传递给 Array,则可以实例化具有给定条目数的空数组> 构造函数,然后通过 ngFor 对其进行迭代.

You can instantiate an empty array with a given number of entries if you pass an int to the Array constructor and then iterate over it via ngFor.

在您的组件代码中:

export class ForLoop {
  fakeArray = new Array(12);
}

在您的模板中:

<ul>
  <li *ngFor="let a of fakeArray; let index = index">Something {{ index }}</li>
</ul>

索引属性为您提供迭代次数.

The index properties give you the iteration number.

现场版