Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 6 set Background Color in Html to CSS Variable

Tags:

html

css

angular

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 passing normal colors. But this does not work with CSS Variables.

This example works

<div [style.background]="'red'">...</div>

This example does not work

<div [style.background]="'var(--some-css-var)'">...</div>
like image 995
Flo Avatar asked Sep 11 '18 18:09

Flo


2 Answers

You have to use ngStyle

<some-element [ngStyle]="{'background-color': styleExp}">...</some-element>

https://angular.io/api/common/NgStyle

like image 127
Gurvinder Guraya Avatar answered Oct 08 '22 16:10

Gurvinder Guraya


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:

<div [style.background-color]="'var(--some-css-var)' | safeStyle"></div>
<div [style.background-color]="bkColor | safeStyle"></div>
bkColor = "var(--some-css-var)";

See this stackblitz for a demo.

like image 28
ConnorsFan Avatar answered Oct 08 '22 18:10

ConnorsFan