方法 * ngFor 循环定义次数而不是重复遍历数组?

有没有一种方法可以让 * ngFor 循环定义次数,而不必总是在数组上迭代?

例如,我希望一个列表重复5次,循环类似于 C # ;

for (int i = 0; i < 4; i++){


}

预期结果:

<ul>
<li><span>1</span></li>
<li><span>2</span></li>
<li><span>3</span></li>
<li><span>4</span></li>
<li><span>5</span></li>
</ul>
149177 次浏览

Within your component, you can define an array of number (ES6) as described below:

export class SampleComponent {
constructor() {
this.numbers = Array(5).fill(0).map((x,i)=>i);
}
}

See this link for the array creation: Tersest way to create an array of integers from 1..20 in JavaScript.

You can then iterate over this array with ngFor:

@View({
template: `
<ul>
<li *ngFor="let number of numbers">\{\{number}}</li>
</ul>
`
})
export class SampleComponent {
(...)
}

Or shortly:

@View({
template: `
<ul>
<li *ngFor="let number of [0,1,2,3,4]">\{\{number}}</li>
</ul>
`
})
export class SampleComponent {
(...)
}

Hope it helps you, Thierry

Edit: Fixed the fill statement and template syntax.