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 want to know if there is any other way of doing this.
HTML
<div *ngFor="#employee of employees; #index = index" [class.odd]="index%2==1" [class.even]="index%2==0" [class.selected]="employee === selectedEmployee">
<p>{{employee.name}}</p>
</div>
CSS
.odd {
background-color: #f2f9ff;
}
.even {
background-color: #eceff3;
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With