Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 868
Angel Angel Avatar asked Feb 18 '16 03:02

Angel Angel


2 Answers

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

like image 73
Sasxa Avatar answered Oct 19 '22 01:10

Sasxa


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.

like image 45
Evan Plaice Avatar answered Oct 19 '22 02:10

Evan Plaice