WARNING: sanitizing unsafe style value background-color
19,082
I've just had the same problem. I've solved it with this balise (Thanks to Sape The Mape) :
[ngStyle]="{'background-color': item.color}"
I wanted to deepen, and I've found this nice article about style within Angular : dynamic styles and this official documentation about binding style
Hope it helps you too :)
Related videos on Youtube
Author by
cfoster5
Updated on September 14, 2022Comments
-
cfoster5 about 1 year
Using Angular, I am pulling data from Firebase. I want user's chat messages to be based on a color that the user chooses,
item.color
. For a user that uses blue, I'm gettingWARNING: sanitizing unsafe style value background-color:blue (see http://g.co/ng/security#xss).
My HTML:
<div *ngFor="let item of items; let i = index"> <ion-card style="background-color:{{item.color}}" [ngClass]="{'me': item.sender == sender, 'notme': item.sender != sender}"> <ion-card-header *ngIf="item.sender != sender"> @{{item.sender}} </ion-card-header> <ion-card-content> {{item.message}} </ion-card-content> </ion-card> </div>
My TS:
import { Component, OnInit, ViewChild } from '@angular/core'; import { AngularFireDatabase, FirebaseListObservable } from 'angularfire2/database-deprecated'; import { AngularFireAuth } from 'angularfire2/auth'; import { Observable } from 'rxjs/Observable'; import * as firebase from 'firebase/app'; import { DomSanitizer } from '@angular/platform-browser'; @Component({ selector: 'page-chat', templateUrl: 'chat.html' }) export class ChatPage{ @ViewChild(Content) content: Content; user: {}; style; ionViewDidLoad(){ firebase.auth().onAuthStateChanged((user)=> { this.user = user; console.log('authState',user); if (user) { var uid = user.uid; firebase.database().ref('/userprofile/' + uid + '/' + 'chatcolor').once('value').then((snapshot)=> { this.color = (snapshot.val()); }); } }); } constructor(public af: AngularFireDatabase, private Svc: Service, private sanitizer: DomSanitizer) { this.style = sanitizer.bypassSecurityTrustStyle("blue") } }
What do I need to do to be able to do this?
-
Sam S almost 6 yearsHave you tried ngStyle
<ion-card [ngStyle]="{ 'background-color': item.color }" [ngClass]="{'me': item.sender == sender, 'notme': item.sender != sender}">
?
-
-
Maxim Mazurok over 5 yearsThanks! Solved same issue with
background-image
:[ngStyle]="{'background-image': 'url('+object.image+')'}"