本文介绍了Angular 2 - NgFor 使用数字代替集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
...例如...
...
可以做类似...
...
...没有诉诸非优雅的解决方案,例如:
<div class="month" *ngFor="#item of ['dummy','dummy','dummy','dummy','dummy','dummy','dummy','dummy'];#i = 索引">...
?
解决方案
在你的组件中,你可以定义一个数字数组 (ES6),如下所述:
导出类 SampleComponent {构造函数(){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]}}
请参阅此链接以创建数组:在 JavaScript 中从 1..20 创建整数数组的最简单方法.
然后你可以用 ngFor
遍历这个数组:
@Component({模板:`<ul><li *ngFor="let number of numbers">{{number}}</li>`})导出类 SampleComponent {(...)}
或者很快:
@Component({模板:`<ul><li *ngFor="let number of [0,1,2,3,4]">{{number}}</li>`})导出类 SampleComponent {(...)}
...for example...
<div class="month" *ngFor="#item of myCollection; #i = index">
...
</div>
Is possible to do something like...
<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>
?
解决方案
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.
You can then iterate over this array with ngFor
:
@Component({
template: `
<ul>
<li *ngFor="let number of numbers">{{number}}</li>
</ul>
`
})
export class SampleComponent {
(...)
}
Or shortly:
@Component({
template: `
<ul>
<li *ngFor="let number of [0,1,2,3,4]">{{number}}</li>
</ul>
`
})
export class SampleComponent {
(...)
}
这篇关于Angular 2 - NgFor 使用数字代替集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!