Angular 2 - コレクションの代わりに数値を使用するNgFor 質問する

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>

?

ベストアンサー1

コンポーネント内では、以下のように数値の配列 (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 {
  (...)
}

おすすめ記事