96

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?

0

14 Answers 14

90

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>
Sign up to request clarification or add additional context in comments.

5 Comments

Nice solution you provide, I'm just astounded how dumb this seems. I just wanted to make a simple for loop, displaying a <p> tag count : int amount of times, my property's number is.
@Esten my bad. I removed the wrong information, thanks for heads up :)
createRange(number) { return new Array(number); }
slightly better solution than @HebertLima { return Array.from(new Array(number).keys()); } or { return [...new Array(number).keys()]; } - this way array get values
@DamianPioś thanks for the suggestion, I have used a suggestion with slight modification.
51

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

1 Comment

Nice solution, in addition I would wrap the new Array(i); in a pipe so that it would be reusable <li *ngFor="let a of 12 | fakeArray; let index = index">Something {{ index }}</li>, pipe code: transform(i: number) { return new Array(i) };
37

Depending on the length of the wanted loop, maybe even a more "template-driven" solution:

<ul>
  <li *ngFor="let index of [0,1,2,3,4,5]">
    {{ index }}
  </li>
</ul>

3 Comments

This is the winner for simple iterators
again, the question simply is for (let i = 0; i < n; i++) {}. If there is None, and the only way to do it, is to use an away, .. then that is the answer to the question... not 'how' to generate an array of size n.
Perfect for small arrays 👍
31

You can do both in one if you use index

<div *ngFor="let item of items; let myIndex = index>
  {{myIndex}}
</div>

With this you can get the best of both worlds.

4 Comments

good suggestion except this requires you to already have an array to loop over or at least count. It doesn't really work if you simply need to loop n times
This worked for nicely for me on 4.2.4^ still. Just wanted to write this since some Angular 2+ is still in flux. I was looking to just get the iterations of an existing array printed in a table and this is the most succinct and elegant solution (IMO)
Are you not missing a closing quote here?
sorry, but -1 for not providing the answer to the question - in the suggested solution, the iteration is on an array and not a number that represents a simple count for the loop.
8

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

Comments

1
   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

Comments

1

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>

1 Comment

Could you elaborate on the statement No imports required? Judging from your example it seems you need to import * as _ from 'lodash' or something similar.
1

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>

Comments

0

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>

Comments

0

You can do like this in a simple way,

<div *ngFor="let i of ('a,'.repeat(100).split(','))">
    .....
</div>

('a,'.repeat(100).split(',')) --> it means construct a long concatenated string of a, 100 times and then split it by , results in array of 100 items, which ngFor picks up and iterate 100 times.

Comments

0

1.generate a pipe for example "ng g p range"

transform(length: number):any[]{
        return new Array(length);
    }

2.in html

 <div *ngFor="let _ of (12|range)" >  ...   </div>

Comments

0

I would suggest a spread operator in a loop like this, if you're using Angular :

this.triggersList = res.content;
      for (let index = 0; index < 10; index++) {
          this.triggersList.push(...this.triggersList);
      }
      this.totalItems = res.totalElements;

*Believing the original question could be expanded to the correct use of the engine, populating the html's list all the same.

Comments

-1

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>

1 Comment

ngfor is correct but question is to range of numbers. similar to for(i=0;i<=5; i++), but this answer is for ngfor rotating objects
-5

If you want duplicate lines multiple time.

You can simply do :-

declare in .ts file

public repeater = "<li>Something</li>";

Then use following to print it .html file.

{{repeater.repeat(5)}}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.