mdline
October 2, 2017, 12:37pm
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>
What is $index%2 in this case?
mdline
October 2, 2017, 12:39pm
3
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?
mdline
October 2, 2017, 12:43pm
5
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.
mdline
October 2, 2017, 12:48pm
7
cars : [{mark: "...", vendor: "...", name: "..."}]
But I want to display each displayed item in another background color.
Refering you to this answer:
mdline
October 2, 2017, 2:53pm
9
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.
This:
color="$index%2 != 0 ? 'lightgrey' : 'grey'"
becomes:
[color]="$index%2 != 0 ? 'lightgrey' : 'grey'"
2 Likes
Just a note that ngFor
has odd
and even
reference variables, which I personally find more readable than index%2
.
1 Like
You have to do this:
<ion-item [color]="even? 'primary' : 'secondary'" *ngFor="let item of itemList; let even = even">
1 Like
o8thug
October 1, 2019, 11:47am
14
*ngFor = "let item of detai |let i=index;" [ngClass]="(i % 2 == 0) ? 'odd' : 'even'"
try this