Alternate color for ionic-item



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

    <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>
      {{ }}<br>


What is $index%2 in this case?


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


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


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


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.

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

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


Refering you to this answer:


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


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


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

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

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


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


You have to do this:

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