ngFor using ngClass on rows and columns issue

后端 未结 4 1895
忘掉有多难
忘掉有多难 2020-12-15 19:07

I am using Angular2 and its ngFor. I want to add class to odd and to even rows, so I can separate them visually by color.

Here is my code (which does not work really

相关标签:
4条回答
  • 2020-12-15 19:24

    worked for me

    <ion-card *ngFor ="let item of itemsCat; let odd=odd; let even=even " [ngClass]="{ odd: odd, even:even}" >
    .....
    </ion-card>
    
    0 讨论(0)
  • 2020-12-15 19:35

    Your first code example is working fine Plunker example

    @Component({
      selector: 'my-app',
      styles: [`
        .even { color: red; }
        .odd { color: green; }
        `],
      template: `
      <h2>Hello {{name}}</h2>
      <div *ngFor="let meeting of meetingList; let index=index; let odd=odd; let even=even;"
          class="row"
          [ngClass]="{ odd: odd, even: even }">{{meeting}}
        <div class="col"></div>
        <div class="col"></div>
      </div>
    `
    })
    export class App {
      meetingList = ['a', 'b', 'c'];
    }
    

    0 讨论(0)
  • 2020-12-15 19:41

    If it's not odd, then it's even anyway. So, save a few bytes and cycles:

    <div *ngFor="let meeting of meetingList; let odd = odd" [ngClass]="odd ? 'odd' : 'even'">
        {{meeting}}
    </div>
    

    You can go even furter and do it only in css, using the nth-child selector with the odd keyword:

    <style> 
    p:nth-child(odd) {
      background: gray;
    }
    
    p:nth-child(even) {
      background: white;
    }
    </style>
    
    <p>First paragraph.</p>
    <p>Second paragraph.</p>
    <p>Third paragraph.</p>
    <p>Fourth paragraph.</p>

    0 讨论(0)
  • 2020-12-15 19:42

    let index=index;

    then [index] = index;

    then [class.odd] = "index%2";

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