ngFor using ngClass on rows and columns issue
Asked Answered
H

4

20

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):

<div *ngFor="#meeting of meetingList; #index=index; #odd=odd; #even=even;"
  class="row"
  [ngClass]="{ odd: odd, even: even }
">
  <div class="col"></div>
  <div class="col"></div>
</div>

Although if I do it like this, code works:

<div *ngFor="#meeting of meetingList; #index=index; #odd=odd; #even=even;"
  class="row"
">
  <div class="col" [ngClass]="{ odd: odd, even: even }"></div>
  <div class="col" [ngClass]="{ odd: odd, even: even }"></div>
</div>

Is there any better way to put class to row instead to columns? Thank you in advance.

Heffernan answered 2/4, 2016 at 16:18 Comment(4)
<div *ngFor="#meeting of meetingList; #index=index; #odd=odd; #even=even;" [class.odd]="odd" [class.even]="even" class="row">Dudleyduds
This is no different as my solution, I think the problem is where you try to add the class - what level. Thank you anyways.Heffernan
Is there any better way to put class to row instead to columns?, what that does mean then?Dudleyduds
@EricMartinez thank you, it is solved.Heffernan
M
46

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'];
}

enter image description here

Mather answered 2/4, 2016 at 16:32 Comment(3)
Thank you, I had a mistake in my CSS.Heffernan
Do you have any idea for odd even even odd odd even odd .. rotation?Trinitrophenol
@Trinitrophenol Should be easy to calculate the color based on the index.Russel
B
4

let index=index;

then [index] = index;

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

Blackboard answered 16/9, 2016 at 18:32 Comment(0)
C
3

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>
Cleghorn answered 21/8, 2019 at 12:4 Comment(0)
B
1

worked for me

<ion-card *ngFor ="let item of itemsCat; let odd=odd; let even=even " [ngClass]="{ odd: odd, even:even}" >
.....
</ion-card>
Bootlick answered 25/4, 2017 at 13:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.