Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Repeat HTML element multiple times using ngFor based on a number

Tags:

angular

<ng-container *ngFor="let i of [].constructor(20)">🐱</ng-container>

generates 🐱🐱🐱🐱🐱🐱🐱🐱🐱🐱🐱🐱🐱🐱🐱🐱🐱🐱🐱🐱


You could use the following:

@Component({
  (...)
  template: `
    <div *ngFor="let i of Arr(num).fill(1)"></div>
  `
})
export class SomeComponent {
  Arr = Array; //Array type captured in a variable
  num:number = 20;
}

Or implement a custom pipe:

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

@Pipe({
  name: 'fill'
})
export class FillPipe implements PipeTransform {
  transform(value) {
    return (new Array(value)).fill(1);
  }
}

@Component({
  (...)
  template: `
    <div *ngFor="let i of num | fill"></div>
  `,
  pipes: [ FillPipe ]
})
export class SomeComponent {
  arr:Array;
  num:number = 20;
}

<div *ngFor="let dummy of ' '.repeat(20).split(''), let x = index">

Replace 20 with your variable


There are two problems with the recommended solutions using Arrays:

  1. It's wasteful. In particular for large numbers.
  2. You have to define them somewhere which results in a lot of clutter for such a simple and common operation.

It seems more efficient to define a Pipe (once), returning an Iterable:

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

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

Usage example (rendering a grid with dynamic width / height):

<table>
    <thead>
      <tr>
        <th *ngFor="let x of colCount|times">{{ x }}</th>
      </tr>
    </thead>
    <tbody>
      <tr *ngFor="let y of rowCount|times">
        <th scope="row">{{ y }}</th>
        <td *ngFor="let x of colCount|times">
            <input type="checkbox" checked>
        </td>
      </tr>
    </tbody>
</table>

You can simple do this in your HTML:

*ngFor="let number of [0,1,2,3,4,5...,18,19]"

And use the variable "number" to index.