本文介绍了Angular 2-NgFor使用数字代替集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
...例如...
<div class="month" *ngFor="#item of myCollection; #i = index">
...
</div>
可以做类似...
<div class="month" *ngFor="#item of 10; #i = index">
...
</div>
...没有吸引力的解决方案,例如:
...without appeal to a non elegant solution like:
<div class="month" *ngFor="#item of ['dummy','dummy','dummy','dummy','dummy',
'dummy','dummy','dummy']; #i = index">
...
</div>
?
推荐答案
在您的组件内,您可以定义一个数字数组(ES6),如下所述:
Within your component, you can define an array of number (ES6) as described below:
export class SampleComponent {
constructor() {
this.numbers = Array(5).fill().map((x,i)=>i); // [0,1,2,3,4]
this.numbers = Array(5).fill(4); // [4,4,4,4,4]
}
}
请参见以下链接以创建数组:.
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
:
@Component({
template: `
<ul>
<li *ngFor="let number of numbers">{{number}}</li>
</ul>
`
})
export class SampleComponent {
(...)
}
或者不久之后:
@Component({
template: `
<ul>
<li *ngFor="let number of [0,1,2,3,4]">{{number}}</li>
</ul>
`
})
export class SampleComponent {
(...)
}
这篇关于Angular 2-NgFor使用数字代替集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!