I am using Angular 6 and I have a simple div
and want to set the background color of this div
from inside the template. This works fine when passin
In order to bind a style property to a CSS variable in the HTML template, the CSS variable expression var(...)
must be sanitized. You can define a custom pipe:
import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer, SafeStyle } from '@angular/platform-browser';
@Pipe({
name: 'safeStyle'
})
export class SafeStylePipe implements PipeTransform {
constructor(private sanitizer: DomSanitizer) { }
transform(value: string): SafeStyle {
return this.sanitizer.bypassSecurityTrustStyle(value);
}
}
and use it in the HTML template:
bkColor = "var(--some-css-var)";
See this stackblitz for a demo.