Dynamically update color on an ion-item

I’ve tried a few things to dynamically change the color of an ion-item such as [color] with a conditional statement and also ngClass but then the style of the ion-item goes blank. I can’t seem to find the right documentation on this if its possible and anything that is online is old and not on the most recent Ionic 6 version.

  • Using latest Angular/Ionic

Two examples I tried with no luck (there is a CSS class shadedItem that has background color set):

.shadedItem {
  background-color: aqua;
}
<ion-item *ngFor="let item of items" [ngClass]="{'shadedItem': item.ID === selectedItem.ID}">
<ion-item *ngFor="let item of items" [color]="item.ID === selectedItem.ID ? 'primary' : 'secondary'">

Results on both showing below:

The item selection maybe change so I wanted the coloring to be dynamic

Maybe you can try --background instead:

.shadedItem {
 --background: aqua;
}

Source: ion-item: Input, Edit, or Delete iOS and Android Item Elements

1 Like

I think the bug is caused by the item.ID === selectedItem.ID part.

I made an example to reproduce the behavior:

In the example, the value of selectedItem might be undefined or null.

When the value of selectedItem is undefined or null, the item.ID === selectedItem.ID check will cause error and make <ion-item> go blank.

Changing the comparison part to selectedItem && item.ID === selectedItem.ID should be able to solve the issue.

screen recording

1 Like

Thank you gents! I ended up using ngclass:


    <ion-item [ngClass]="item.itemSelected ? 'shadedBackground' : ''">

CSS:

.shadedBackground {
  filter: brightness(80%);
  border: 2px solid #808080;
}
.dark .shadedBackground {
  filter: brightness(110%);
}
1 Like