ebakunin ebakunin - 4 months ago 105
AngularJS Question

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="#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?

Answer

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="#item of createRange(5); #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;
}

Demo Here

Comments