Angular 2-NgFor使用数字代替集合

...例如...


<div class="month" *ngFor="#item of myCollection; #i = index">

...

</div>

可以做类似...


<div class="month" *ngFor="#item of 10; #i = index">

...

</div>

...没有吸引力的解决方案,例如:


<div class="month" *ngFor="#item of ['dummy','dummy','dummy','dummy','dummy',

'dummy','dummy','dummy']; #i = index">

...

</div>


收到一只叮咚
浏览 1910回答 3
3回答

陪伴而非守候

在组件内,您可以定义一个数字数组(ES6),如下所述:export class SampleComponent {&nbsp; constructor() {&nbsp; &nbsp; this.numbers = Array(5).fill().map((x,i)=>i); // [0,1,2,3,4]&nbsp; &nbsp; this.numbers = Array(5).fill(4); // [4,4,4,4,4]&nbsp; }}请参阅此链接以获取数组创建:在JavaScript中从1..20创建整数数组的最有趣的方法。然后可以使用以下方法遍历此数组ngFor:@Component({&nbsp; template: `&nbsp; &nbsp; <ul>&nbsp; &nbsp; &nbsp; <li *ngFor="let number of numbers">{{number}}</li>&nbsp; &nbsp; </ul>&nbsp; `})export class SampleComponent {&nbsp; (...)}或不久:@Component({&nbsp; template: `&nbsp; &nbsp; <ul>&nbsp; &nbsp; &nbsp; <li *ngFor="let number of [0,1,2,3,4]">{{number}}</li>&nbsp; &nbsp; </ul>&nbsp; `})export class SampleComponent {&nbsp; (...)}

慕容3067478

您与“非优雅”解决方案非常接近。怎么样:<div class="month" *ngFor="let item of [].constructor(10); let i = index">...</div>在这里,我Array从一个空数组获取构造函数:[].constructor,因为Array在模板语法中它不是公认的符号,而且我也懒得去做,Array=Array或者counter = Array像@ pardeep-jain在他的第四个示例中那样在组件打字稿中也懒得做。我new之所以这么称呼它,是因为new不需要从Array构造函数中获取数组。Array(30)和new Array(30)等价。该数组将为空,但这没关系,因为您真的只想在循环中使用ifrom ;let i = index。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

AngularJS