124

Is there a way to *ngFor loop a defined number of times instead of always having to iterate over an array?

For example, I want a list to repeat 5 times, the loop would be something like that in C#;

for (int i = 0; i < 4; i++){

}

Desired result:

<ul>
   <li><span>1</span></li>
   <li><span>2</span></li>
   <li><span>3</span></li>
   <li><span>4</span></li>
   <li><span>5</span></li>
</ul>
1
  • 1
    one method is as said by @TGH and second one you can use your for loop as mentioned in question then push value of [i] in empty array and start *ngFor on that array this is also possible. you can chose either one from these two way. Commented Dec 22, 2015 at 5:12

1 Answer 1

128

Within your component, you can define an array of number (ES6) as described below:

export class SampleComponent {
  constructor() {
    this.numbers = Array(5).fill(0).map((x,i)=>i);
  }
}

See this link for the array creation: Tersest way to create an array of integers from 1..20 in JavaScript.

You can then iterate over this array with ngFor:

@View({
  template: `
    <ul>
      <li *ngFor="let number of numbers">{{number}}</li>
    </ul>
  `
})
export class SampleComponent {
  (...)
}

Or shortly:

@View({
  template: `
    <ul>
      <li *ngFor="let number of [0,1,2,3,4]">{{number}}</li>
    </ul>
  `
})
export class SampleComponent {
  (...)
}

Hope it helps you, Thierry

Edit: Fixed the fill statement and template syntax.

Sign up to request clarification or add additional context in comments.

16 Comments

I think the Array(5).fill()... is missing a 0. It should be Array(5).fill(0). From the docs developer.mozilla.org/en/docs/Web/JavaScript/Reference/…
<li *ngFor="let i of [].constructor(5)"></li >
To get exactly what the OP wants (each li containing a sequential number starting at 1), extend @olNoy's answer: <li *ngFor="let e of [].constructor(5); let i = index"><span>{{i+1}}</span></li>
@DanielFlippance why haven't you posted the answer instead of a comment.
@MeVimalkumar This question appears only allow comments at this time
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.