91

Using Angular 2, I want to duplicate a line in a template multiple times. Iterating over an object is easy, *ngFor="let object of objects". However, I want to run a simple for loop, not a foreach loop. Something like (pseudo-code):

{for i = 0; i < 5; i++}
  <li>Something</li>
{endfor}

How would I do this?

ebakunin
  • 3,621
  • 7
  • 30
  • 49

13 Answers13

89

You could dynamically generate an array of however time you wanted to render <li>Something</li>, and then do ngFor over that collection. Also you could take use of index of current element too.

Markup

<ul>
   <li *ngFor="let item of createRange(5); let currentElementIndex=index+1">
      {{currentElementIndex}} Something
   </li>
</ul>

Code

createRange(number){
  // return new Array(number);
  return new Array(number).fill(0)
    .map((n, index) => index + 1);
}

Demo Here

Under the hood angular de-sugared this *ngFor syntax to ng-template version.

<ul>
    <ng-template ngFor let-item [ngForOf]="createRange(5)" let-currentElementIndex="(index + 1)" [ngForTrackBy]="trackByFn">
      {{currentElementIndex}} Something
    </ng-template>
</ul>
Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299
48

You can instantiate an empty array with a given number of entries if you pass an int to the Array constructor and then iterate over it via ngFor.

In your component code :

export class ForLoop {
  fakeArray = new Array(12);
}

In your template :

<ul>
  <li *ngFor="let a of fakeArray; let index = index">Something {{ index }}</li>
</ul>

The index properties give you the iteration number.

Live version

Sbats
  • 515
  • 6
  • 3
  • 3
    Nice solution, in addition I would wrap the `new Array(i);` in a pipe so that it would be reusable `
  • Something {{ index }}
  • `, pipe code: `transform(i: number) { return new Array(i) };` – Felix Feb 14 '20 at 15:38