Angular 2 - NgFor using numbers instead collections

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

@OP, you were awfully close with your "non-elegant" solution.

How about:

<div class="month" *ngFor="let item of [].constructor(10); let i = index">
...
</div>

Here I'm getting the Array constructor from an empty array: [].constructor, because Array isn't a recognized symbol in the template syntax, and I'm too lazy to do Array=Array or counter = Array in the component typescript like @pardeep-jain did in his 4th example. And I'm calling it without new because new isn't necessary for getting an array out the Array constructor.

Array(30) and new Array(30) are equivalent.

The array will be empty, but that doesn't matter because you really just want to use i from ;let i = index in your loop.

Edit to respond to comments:

Q. How can I use a variable to set the length of the NgFor loop?

Here is an example on how to render a table with variable columns/rows

<table class="symbolTable">
  <tr *ngFor="let f of [].constructor(numRows); let r = index">
    <td class="gridCell" *ngFor="let col of [].constructor(numCols); let c = index">
      {{gridCards[r][c].name}}
    </td>
  </tr>
</table>
export class AppComponent implements OnInit {
  title = 'simbologia';
  numSymbols = 4;
  numCols = 5;
  numRows = 5;
  guessCards: SymbolCard[] = [];
  gridCards: SymbolCard[][] = [];

  ngOnInit(): void {
    for (let c = 0; c < this.numCols; c++) {
      this.guessCards.push(new SymbolCard());
    }

    for (let r = 0; r < this.numRows; r++) {
      let row: SymbolCard[] = [];

      for (let c = 0; c < this.numCols; c++) {
        row.push(
          new SymbolCard({
            name: '' + r + '_' + c
          }))
      }
      this.gridCards.push(row);
    }
  }
}

Tags:

Angular