ebakunin ebakunin - 1 year ago 270
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
loop, not a
loop. Something like (pseudo-code):

{for i = 0; i < 5; i++}

How would I do this?

Answer Source

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.


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


  var items: number[] = [];
  for(var i = 1; i <= number; i++){
  return items;

Demo Here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download