angular: how to loop for numbers?

You can use javascript inside *ngFor so the solution could look like this:

my.component.ts

counter(i: number) {
    return new Array(i);
}

my.component.html

<li *ngFor='let in of counter(5) ;let i = index'>{{i}}</li>

If you want to implement this in the canonical Angular way, you could create a range pipe which produces the array on the spot.

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

@Pipe({
  name: 'range'
})
export class RangePipe implements PipeTransform {
  transform(length: number, offset: number = 0): number[] {
    if (!length) {
      return [];
    }
    const array = [];
    for (let n = 0; n < length; ++n) {
      array.push(offset + n);
    }
    return array;
  }
}

And then you would use it in a template like this:

<ul>
  <li *ngFor="let n of item.rank | range">
    <img src="star.png">
  </li>
</ul>

The offset parameter is useful when you don't want the array to start at 0, of course.

A massive upside of this approach is that this is a pure pipe, meaning it will only be executed if item.rank changes. Other approaches may update spuriously on any arbitrary page check phase (potentially many times per second).


Maybe the simplest solution without any TS code:

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

Tags:

Angular

Ngfor