I tried to implement ng-class-even and ng-class-odd ( from angular 1) type behaviour in angular 2 application.
I have written the code below and its working fine, I
OLD way
DEMO : http://plnkr.co/edit/YkcudQipF1c8iT5LCRyd?p=preview
<div *ngFor="#employee of employees;
#index =index;
#isOdd=odd;
#isEven=even"
[class.odd]="isOdd"
[class.even]="isEven"
[class.selected]="employee === selectedEmployee">
<p>{{employee.name}}</p>
</div>
replace #
by let
(keyword)
<div *ngFor="let employee of employees;
let index =index;
let isOdd=odd;
let isEven=even"
[class.odd]="isOdd"
[class.even]="isEven"
[class.selected]="employee === selectedEmployee">
<p>{{employee.name}}</p>
</div>
update (Angular4)
<div *ngFor="let employee of employees; index as i; odd as isOdd; even as isEven"
original (Angular2)
This should work:
<div *ngFor="let employee of employees; let index = index; let isOdd=odd; let isEven=even"
[class.Odd]="isOdd"
[class.even]="isEven"
[class.selected]="employee === selectedEmployee">
<p>{{employee.name}}</p>
</div>
NgFor
provides several exported values that can be aliased to local variables:
index
will be set to the current loop iteration for each template context.first
will be set to a boolean value indicating whether the item is the first one in the iteration. (since beta.15)last
will be set to a boolean value indicating whether the item is the last one in the iteration.even
will be set to a boolean value indicating whether this item has an even index.odd
will be set to a boolean value indicating whether this item has an odd index.
Plunker
See also https://angular.io/docs/ts/latest/api/common/index/NgFor-directive.html
<div *ngFor="#employee of employees; #index = index;#isOdd=odd;#isEven=even"
[class.Odd]="isOdd"
[class.even]="isEven"
[class.selected]="employee === selectedEmployee">
<p>{{employee.name}}</p>
</div>
The above code worked fine.
Thanks Gunter, micronyks.