Ionic 4 - How to set CSS Custom Properties dynamically


#1

Has anyone figured out how to setup Ionic 4’s CSS Customer Properties dynamically? eg --background

I’ve tried below without much luck.

<ion-item button="true" (click)="action(state)" [style.--background]="colorVar" margin>           
   Some values
</ion-item>

where in component

this.colorVar = "blue"


#2

Hello,
try with class="example" instead of [style.–background]=“blue” in html
and in the .scss =>
.example { background: blue; margin: ..... }
I do not know if it’s the best solution but I put my css like that


#3

Is this what you’re looking for?

ion-item {
    --background: var(--ion-color-primary);
    //Or 
    --background: #cccccc;
}

Ion item css properties


#4

I just did it at the moment
in . html

  <ion-item class="item">
  </ion-item>

in .SCSS

.item{
    --ion-background-color:grey;
}

it works well. it all depends if we want all the <ion-items> to take the same property or not


#5

Sorry all I should have been explicit when I meant dynamic. I want to set the background where the color is a variable as follows (as well as updating my original question):

[style.–background]=“colorVar”

This doesn’t work in Ionic. I actually found a solution but not sure if this the best practice as it requires the sanitizer. Keen on anyone’s else alternative on how to do this?

SCSS

.action {
    --background: var(--myvar);
}

Component

value: string = "blue";
  @HostBinding("attr.style")
  public get valueAsStyle(): any {
    return this.sanitizer.bypassSecurityTrustStyle(`--myvar: ${this.value}`);
  }

Html

<ion-item button=“true” (click)=“action(state)” class="action">
Some Content
</ion-item>