Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Way to *ngFor loop defined number of times instead of repeating over array? [duplicate]

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>
like image 786
Rodrigo Real Avatar asked Dec 21 '15 23:12

Rodrigo Real


Video Answer


1 Answers

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.

like image 97
Thierry Templier Avatar answered Sep 28 '22 01:09

Thierry Templier