Interpolate style in angular won't work (Ionic 5)

76 views Asked by At

I'm trying this in Ionic 5 and it works:

<ion-content style="--background: yellow;">

However I want to change the color dinamically. I've tried this with no success:

<ion-content [ngStyle]="{'--background': backgroundColor}">

I can't find the mistake.

1

There are 1 answers

1
Alberto Chiesa On BEST ANSWER

NgStyle does not support css variables.
It's a "known" limitation and it's been for quite a while:
https://github.com/angular/angular/issues/9343

There are workarounds, however, even if somewhat ugly. My preferred is this:

<ion-content [attr.style]="sanitizer.bypassSecurityTrustStyle('--background: ' + backgroundColor)">
// you will need a DomSanitizer instance in your component
constructor(private sanitizer: DomSanitizer) {}