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

Viewed 269612

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?

11 Answers

The better way to do this is creating a fake array in component:

In Component:

fakeArray = new Array(12);

InTemplate:

<ng-container *ngFor = "let n of fakeArray">
     MyCONTENT
</ng-container>

Plunkr here

you can use _.range([optional] start, end). It creates a new Minified list containing an interval of numbers from start (inclusive) until the end (exclusive). Here I am using lodash.js ._range() method.

Example:

CODE

var dayOfMonth = _.range(1,32);  // It creates a new list from 1 to 31.

//HTML Now, you can use it in For loop

<div *ngFor="let day of dayOfMonth">{{day}}</div>
   queNumMin = 23;
   queNumMax= 26;
   result = 0;
for (let index = this.queNumMin; index <= this.queNumMax; index++) {
         this.result = index
         console.log( this.result);
     }

Range min and max number

for Example let say you have an array called myArray if you want to iterate over it

<ul>
  <li *ngFor="let array of myArray; let i = index">{{i}} {{array}}</li>
</ul>

The best answer for this question I have found here

You need to create an attribute inside your class and reference it to Array object:

export class SomeComponent {
  Arr = Array; //Array type captured in a variable
  num:number = 20;
}

And inside your HTML you can use:

<ul id="next-pages">
    <li class="line" *ngFor="let _ of Arr(10)">&nbsp;</li>
</ul>

If you want to use the object of ith term and input it to another component in each iteration then:

<table class="table table-striped table-hover">
  <tr>
    <th> Blogs </th>
  </tr>
  <tr *ngFor="let blogEl of blogs">
    <app-blog-item [blog]="blogEl"> </app-blog-item>
  </tr>
</table>

You can simply do :-

{{"<li>Something</li>".repeat(5)}}
Related