* ngFor循环定义次数而不是在数组上重复的方法? [英] Way to *ngFor loop defined number of times instead of repeating over array?
本文介绍了* ngFor循环定义次数而不是在数组上重复的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有一种方法可以* ngFor循环定义的次数,而不必总是遍历数组?
Is there a way to *ngFor loop a defined number of times instead of always having to iterate over an array?
例如,我希望一个列表重复5次,循环将类似于C#中的内容;
For example, I want a list to repeat 5 times, the loop would be something like that in 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>
推荐答案
在您的组件内,您可以定义一个数字数组(ES6),如下所述:
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.
然后可以使用ngFor
遍历此数组:
You can then iterate over this array with ngFor
:
@View({
template: `
<ul>
<li *ngFor="let number of numbers">{{number}}</li>
</ul>
`
})
export class SampleComponent {
(...)
}
或者不久之后:
@View({
template: `
<ul>
<li *ngFor="let number of [0,1,2,3,4]">{{number}}</li>
</ul>
`
})
export class SampleComponent {
(...)
}
希望它对您有帮助, 蒂埃里
Hope it helps you, Thierry
修复了填充语句和模板语法.
Fixed the fill statement and template syntax.
这篇关于* ngFor循环定义次数而不是在数组上重复的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文