'How to use bypassSecurityTrustStyle correctly
I am trying to work with some simple CSS and JavaScript examples in an Angular way.
The plain JavaScript way to change the background color on an element would look something like this:
this.container.style.backgroundColor = color;
The color is created randomly in JavaScript. The template could look like this:
<div id="container"
(click)="changeColor($event)"
[style]="{'color': color}">
</div>
However, this will give the following error:
WARNING: sanitizing unsafe style value [object Object] (see http://g.co/ng/security#xss).
Using this function does not work:
this.color = this.sanitizer.bypassSecurityTrustStyle(this.color);
Creating a function to do it also does not work using this style [style.color]="transform(color)"
transform(value) {
return this.sanitizer.bypassSecurityTrustStyle(value);
}
I have created a plunker to demonstrate this problem.
The correct behaviour using plain JavaScript is shown in the first example on this page
What is the correct way to do this? Any help would be much appreciated.
Solution 1:[1]
The example plunker was using bypassSecurityTrustStyle correctly:
this.color = this.sanitizer.bypassSecurityTrustStyle(this.color);
However, the template needed to set the value like this:
[style.background]="color"
Solution 2:[2]
I think you need to use [styles] or [ngStyle] like this :-
<some-element [ngStyle]="{'font-style': styleExp}">...</some-element>
or
<some-element [styles]="myObj}">...</some-element>
Where in the templates component myObj is myObj = {color: 'red', font-size: '1.1em'}
Docs for [ngStyle] here
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | curchod |
| Solution 2 | Joe Keene |
