警告:清理不安全的样式值background-color

时间:2018-01-25 03:24:04

标签: angular typescript xss

使用Angular,我从Firebase中提取数据。我希望用户的聊天消息基于用户选择的颜色item.color。对于使用蓝色的用户,我收到WARNING: sanitizing unsafe style value background-color:blue (see http://g.co/ng/security#xss).

我的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>

我的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")
  }

}

我需要做什么才能做到这一点?

1 个答案:

答案 0 :(得分:21)

我刚遇到同样的问题。我用这个balise解决了它(感谢Sape The Mape):

[ngStyle]="{'background-color': item.color}"

我想加深,我在Angular中找到了关于样式的好文章:dynamic styles 以及关于binding style

的官方文档

希望它也能帮到你:)。