Search code examples
angularionic4background-colorion-item

Ionic 4 update ion-item background programmatically


I have something like this:

<ion-item>
     <ion-label class="ion-text-center">{{variable}}</ion-label>
</ion-item>

I need to be able to set the background of the ion-item to a colour anywhere between red and green based on the program results, so I am generating a value "{'background-color':'rgb(#,#,0)'}" in the page.ts.

I am unable to use [ngStyle]="{'--ion-background':'rgb(#,#,0)'}" as when the value changes ionic has already expanded the html into its item-native component. I need to be able to access item-native somehow with [ngStyle] or ng-style or maybe something like [.item-native background]?

Or are there easier/better ways to do this?


Solution

  • Set the background of item and the item-native class to transparent using css4 variable; and then set the background style of the ion-item using [ngStyle] depending on the boolean value returned. Example below

    .item {
      --background: transparent !important;
    }
    
    .item .item-native {
       --background: transparent !important;
    }
    

    Then the HTML will look thus:

    <ion-item [ngStyle]="{'background':(true)?'#32db64':'#f53d3d'}">
      <ion-label class="ion-text-center">{{variable}}</ion-label>
    </ion-item>