Angular 2 - NgFor using numbers instead collections

Marco Jr picture Marco Jr · Apr 1, 2016 · Viewed 263.8k times · Source

...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>

?

Answer

Thierry Templier picture Thierry Templier · Apr 1, 2016

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 {
  (...)
}