Javascript *ngFor 循环定义次数而不是重复数组的方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34405878/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Way to *ngFor loop defined number of times instead of repeating over array?
提问by Rodrigo Real
Is there a way to *ngFor loop a defined number of times instead of always having to iterate over an array?
有没有办法 *ngFor 循环定义的次数而不是总是必须遍历数组?
For example, I want a list to repeat 5 times, the loop would be something like that in C#;
例如,我想要一个列表重复 5 次,循环就像 C# 中的那样;
for (int i = 0; i < 4; i++){
}
Desired result:
想要的结果:
<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>
回答by Thierry Templier
Within your component, you can define an array of number (ES6) as described below:
在您的组件中,您可以定义一个数字数组 (ES6),如下所述:
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.
有关创建数组的信息,请参阅此链接:在 JavaScript 中从 1..20 创建整数数组的最简单方法。
You can then iterate over this array with ngFor
:
然后,您可以使用以下命令迭代此数组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.
编辑:修复了填充语句和模板语法。