Angel Angel
Angel Angel

Reputation: 21658

create loop for, in angular 2 from a template

Is possible, use something like the following in a template of angular2,

for int a = 0; a < numberTest; a++

this numberTest is in code component:

numberTest: number = 5;

and the template, something like this, it is better to illustrate what I mean:

<li *ngFor="#int a = 0; a < numberTest">

I know that could be solved using an array, and iterate for example:

<li *ngFor="#item of items">

but my question is, if possible, create a for, in the template, which take the value condition using a variable component, hope I explain well.

Upvotes: 5

Views: 19629

Answers (2)

Evan Plaice
Evan Plaice

Reputation: 14140

NgFor includes an index value for exactly this purpose

No function or intermediate state necessary.

<ul *ngFor="#item of items; #i = index">
  <li *ngIf="i < numberTest">{{ item }}</li>
</ul>

Source: Angualar2 Docs - NgFor

Note: This isn't tested so it may require a little tweaking.

Upvotes: 3

Sasxa
Sasxa

Reputation: 41254

Maybe something like this:

<li *ngFor="#int of range(numberTest)">

with a helper function:

let range = (value) => { 
 let a = []; for(let i = 0; i < value; ++i) { a.push(i+1) } return a; }

http://plnkr.co/edit/CNVqxU?p=preview

Upvotes: 4

Related Questions