Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing ngClassEven ngClassOdd for angular 2

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;
}
like image 977
Anup Malhan Avatar asked Mar 30 '16 16:03

Anup Malhan


2 Answers

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>


New Way

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>
like image 155
Nikhil Shah Avatar answered Sep 18 '22 06:09

Nikhil Shah


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

like image 41
Günter Zöchbauer Avatar answered Sep 19 '22 06:09

Günter Zöchbauer