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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With