Alternate color for ionic-item


#1

Hello,

I want to have an alternated background color. But this does not work. Please help.

 <ion-list>
    <ion-item color="$index%2 != 0 ? 'lightgrey' : 'grey'" *ngFor="let car of cars">
      <div class="item-content">
      <h2> <strong>{{ car.mark }} </strong></h2>
      {{ car.vendor }}<br>
      {{ car.name }}<br>
      </div>
    </ion-item>
  </ion-list>

#2

What is $index%2 in this case?


#3

the index property of the ion-list which gives the index of the current list item.


#4

You tried to console.log() it?
Does it have a value?


#5

no it has no value. But what is the right way to do it.


#6

What data is in car?
Can you give us the information from the let car with a console.log()?

I want to understand why you want to show lightgrey color when it’s not 0.
And show grey color when it’s 0.

Explain little bit more.


#7
cars : [{mark: "...", vendor: "...", name: "..."}]

But I want to display each displayed item in another background color.


#8

Refering you to this answer:


#9

But the ngClassEven or ngClassOdd only works in context with ng-repeat. But I use ngFor.


#10

Then simply, It will maybe work for you to if you got an identifier.
So add an counting ID to your array list and try it again.
(Not sure if it’s going to work).


#11

To bind colour you have to use the [] syntax.

This:
color="$index%2 != 0 ? 'lightgrey' : 'grey'"

becomes:
[color]="$index%2 != 0 ? 'lightgrey' : 'grey'"


#12

Just a note that ngFor has odd and even reference variables, which I personally find more readable than index%2.


#13

You have to do this:

 <ion-item  [color]="even? 'primary' : 'secondary'" *ngFor="let item of itemList; let even = even">