Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get index in a for...of directive in Angular 2

Tags:

angular

As of now, is there a way to get the current index of the iterable in a for..of directive in Angular 2? In others words, the equivalent of $index in Angular.js v1...

Example of code:

<ul *for="#task of allTasks">     <li>{{ $index}} - {{ task.label }}</li> </ul> 

(of course this code does not work, it does not provide the current index)

like image 339
Romain Linsolas Avatar asked Mar 29 '15 21:03

Romain Linsolas


People also ask

What is * ngFor in angular?

*ngFor is a predefined directive in Angular. It accepts an array to iterate data over atemplate to replicate the template with different data. It's the same as the forEach() method in JavaScript, which also iterates over an array.

Why * is used in ngFor?

In *ngFor the * is a shorthand for using the new angular template syntax with a template tag, this is also called structural Directive.It is helpful to know that * is just a shorthand to explicitly defining the data bindings on a template tag.

Can we use ngFor in ng template?

It is used for grouping content that is not rendered, but that can be used in other parts of your code. Alternatively, (and preferably), you can also use the ng-template element by prefixing an asterisk (*), which is the shorthand syntax. For instance, *ngIf, *ngFor.


1 Answers

<ul>     <template ngFor let-task [ngForOf]="allTasks" let-i="index">         <li>{{ i }} - {{ task.label }}</li>     </template> </ul> 

But you have to use the very most recent version of the quickstart

BTW - the above is the equivalent of the following syntax sugar

<li *ngFor="let task of allTasks; let i=index">{{ i }} - {{ task.label }}</li> 
like image 71
unobf Avatar answered Sep 20 '22 08:09

unobf