2

I am trying to learn Angular and I have seen ngFor used to go through arrays, but I can't seem to find anything that simply repeats an html element n amount of times based on a number.

So if I have in the TS file of the component

public rounds: number = 5;

and the HTML

<tr *ngFor=""></tr>

I want the tr to repeat 5 times or however many times based on the value of rounds.

fubar92
  • 85
  • 1
  • 8

1 Answers1

2

Within your component, you can define an array of number (ES6) as described below:

export class SampleComponent {
  constructor() {
    this.numbers = Array(5).fill(0).map((x,i)=>i);
  }
}

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:

<tr *ngFor="let number of numbers">{{number}}</tr>

or if you don't want to define the array in the component you could use:

<tr *ngFor="let number of [0,1,2,3,4]">{{number}}</tr>
James Collins
  • 375
  • 3
  • 7