Using the *ngFor Directive to Repeat n Times in Angular

A few examples of how to use *ngFor to repeat an element a specified number of times.

A Simple Array

Create an Array with the required number of items and then iterate over this array with the *ngFor directive.

array-gen.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-array-gen',
  template: `
    <p>
      <span *ngFor="let item of arrayOne(8); let i = index;">{{i}} </span>
    </p>
    <p>
      <span *ngFor="let i of arrayTwo(12)">{{i}} </span>
    </p>
    <p>
      <span *ngFor="let i of arrayThree(5, 100)">{{i}} </span>
    </p>
  `
})
export class ArrayGenComponent {

arrayOne(n: number): any[] { return Array(n); }
arrayTwo(n: number): number[] { return [...Array(n).keys()]; } arrayThree(n: number, startFrom: number): number[] { return [...Array(n).keys()].map(i => i + startFrom); } }

Use the built-in index value if you need to access the index of the array in the template.

An Array of Integers

Use the spread operator on the array's keys to populate the returned array with incrementing integer values.

array-gen.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-array-gen',
  template: `
    <p>
      <span *ngFor="let item of arrayOne(8); let i = index;">{{i}} </span>
    </p>
    <p>
      <span *ngFor="let i of arrayTwo(12)">{{i}} </span>
    </p>
    <p>
      <span *ngFor="let i of arrayThree(5, 100)">{{i}} </span>
    </p>
  `
})
export class ArrayGenComponent {

  arrayOne(n: number): any[] {
    return Array(n);
  }

arrayTwo(n: number): number[] { return [...Array(n).keys()]; }
arrayThree(n: number, startFrom: number): number[] { return [...Array(n).keys()].map(i => i + startFrom); } }

Note: If you are compiling to ES5 you will need to add this to your tsconfig.json.

"downlevelIteration": true,

Alternatively we can use this slightly longer syntax in the code.
Array.from(Array(n).keys());

Start From

To start from a particular value we can add a map function.

array-gen.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-array-gen',
  template: `
    <p>
      <span *ngFor="let item of arrayOne(8); let i = index;">{{i}} </span>
    </p>
    <p>
      <span *ngFor="let i of arrayTwo(12)">{{i}} </span>
    </p>
    <p>
      <span *ngFor="let i of arrayThree(5, 100)">{{i}} </span>
    </p>
  `
})
export class ArrayGenComponent {

  arrayOne(n: number): any[] {
    return Array(n);
  }

  arrayTwo(n: number): number[] {
    return [...Array(n).keys()];
  }

arrayThree(n: number, startFrom: number): number[] { return [...Array(n).keys()].map(i => i + startFrom); }
}

Here is the output from the component.