Implementing ngClassEven ngClassOdd for angular 2

前端 未结 3 1166
闹比i
闹比i 2020-12-19 01:52

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

相关标签:
3条回答
  • 2020-12-19 02:35

    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>
    
    0 讨论(0)
  • 2020-12-19 02:45

    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

    0 讨论(0)
  • 2020-12-19 02:47
    <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.

    0 讨论(0)
提交回复
热议问题