Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2: How to write a for loop, not a foreach loop

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?

like image 633
ebakunin Avatar asked Mar 18 '16 22:03

ebakunin


People also ask

Can we use for loop in angular?

The for–in loop is for looping over object properties. The for–of loop is for looping over the values in an array. for–of is not just for arrays. It also works on most array-like objects including the new Set and Map types which we will cover in the next lecture.


1 Answers

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){   // var items: number[] = [];   // for(var i = 1; i <= number; i++){   //   items.push(i);   // }   // return items;   return new Array(number); } 

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> 
like image 189
Pankaj Parkar Avatar answered Sep 23 '22 16:09

Pankaj Parkar