Is it possible to apply dynamic style as string in Angular?

Viewed 2977

I have a <span> that I want to apply dynamic style to.

Style is stored in a css-like string variable and can be arbitrary e.g.

myStyle = 'color: white; font-weight: bold;'

or

myStyle = 'background-color: red;'

I expected it to work like

<span style="{{myStyle}}">

but it didn't.

I tried different options but none seem to work for me for different reasons:

  • I can't put styles in a .css file and use class names because style is coming from server in the form of aforementioned string
  • Using [style.color] etc. doesn't suit me because I don't know what the style can be
  • Using [ngStyle] doesn't suit me because it expects object like {'color': 'red', 'font-weight': 'bold'} and I only have string

The reason I have a style stored in a string is because I need to apply it in HTML generated on the server where I simply pass that string to a placeholder variable in a velocity template.

I am almost confident that it can't be done the way I want but probably I am overlooking some solution.

3 Answers

All you need is DomSanitizer and bypassSecurityTrustStyle

Component side :

import { DomSanitizer } from '@angular/platform-browser';

constructor(private doms : DomSanitizer) {}

newStyle = 'background-color:red';

safeCss(style) {
    return this.doms.bypassSecurityTrustStyle(style);
}

Template side :

<p [style]="safeCss(this.newStyle)">
  Start editing to see some magic happen :)
</p>

WORKING DEMO

Angular provides the DomSanitizer service which can convert strings into style objects. I think this is exactly your case.

constructor(private sanitizer: DomSanitizer) {
}

sanitizeStyle() {
    return this.sanitizer.bypassSecurityTrustStyle('background-color: red');
}

<span [style]="sanitizeStyle()">

I think I will go the way of converting the incoming css string into a style object and then applying it to <span> using [ngStyle]

Related