Site Overlay

How to repeat an HTML element or component multiple times in Angular 9/8?

Share : Answer for How to repeat an HTML element or component multiple times in Angular 9/8?

We have multiples solutions for this task. For example, we can use an array with five in length with the ngFor directive:

 

const arr = Array(5);

In your component's template:

<div *ngFor="let e in arr; let i = index">
  {{ e }}
</div>

You can also define and use an Angular Pipe with an Iterable:

 

import {PipeTransform, Pipe} from '@angular/core';

@Pipe({name: 'repeat'})
export class RepeatPipe implements PipeTransform {
  transform(value: number): any {
    const iter = <Iterable<any>> {};
    iter[Symbol.iterator] = function* () {
      let n = 0;
      while (n < value) {
        yield ++n;
      }
    };
    return iter;
  }
}

 

Then, in your template, it can be used as follows to display a DIV element multiple times:

 

      <div *ngFor="let e of n|repeat">
        {{ e }}
      </div>

Also, don't forget to define a typescript variable named n in your component with a value of five.

 

You can also create a custom directive for achieving the same thing.