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>

蒂埃里·坦维尔(Thierry Templier):

在组件内,您可以定义一个数字数组(ES6),如下所述:

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]
  }
}

请参阅此链接以获取数组创建:在JavaScript中从1..20创建整数数组的最有趣的方法

然后,您可以使用以下方法遍历此数组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 {
  (...)
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章