在RC.1中,某些样式不能使用绑定语法添加

样式喜欢

<div [style.background-image]="\'url(\' + image + \')\'">Background</div> <div [style.transform]="rotate(7deg)" 

不再被添加

更新(最终2.0.0)

 import { Pipe, PipeTransform } from '@angular/core'; import { DomSanitizer } from '@angular/platform-browser'; @Pipe({name: 'safeHtml'}) export class SafeHtml implements PipeTransform { constructor(private sanitizer:DomSanitizer){} transform(html) { return this.sanitizer.bypassSecurityTrustStyle(style); // return this.sanitizer.bypassSecurityTrustHtml(style); // return this.sanitizer.bypassSecurityTrustScript(value); // return this.sanitizer.bypassSecurityTrustUrl(value); // return this.sanitizer.bypassSecurityTrustResourceUrl(value); } } 

另请参阅https://angular.io/api/platform-b​​rowser/DomSanitizer

 <div [innerHTML]="someHtml | safeHtml" 

更新

DomSanitizationService将在RC.6中重命名为DomSanitizer

原版的

这应该在RC.2中解决

另请参阅Angular2开发人员指南 – 安全性


Angular2在RC.1中引入了CSS值和属性绑定(如[innerHTML]=...[src]="..."的入侵消毒

另见https://github.com/angular/angular/issues/8491#issuecomment-217467582

通过使用DomSanitizer.bypassSecurityTrustStyle(...)可以将值标记为可信

 import {DomSanitizer} from '@angular/platform-browser'; ... constructor(sanitizer: DomSanitizationService) { this.backgroundImageStyle = sanitizer.bypassSecurityTrustStyle('url(' + this.image + ')'); // for HTML // this.backgroundImageStyle = sanitizer.bypassSecurityTrustHtml(...); } 

并绑定到这个值,而不是不可信的普通string。

这也可以包裹在一个pipe道中

 @Pipe({name: 'safeStyle'}) export class Safe { constructor(private sanitizer:Sanitizer){} transform(style) { return this.sanitizer.bypassSecurityTrustStyle(style); // return this.sanitizer.bypassSecurityTrustHtml(style); // return this.sanitizer.bypassSecurityTrustScript(value); // return this.sanitizer.bypassSecurityTrustUrl(value); // return this.sanitizer.bypassSecurityTrustResourceUrl(value); } } 
 <div [ngStyle]="someStyle | safeStyle"></div> 

 someHtml = `<a href="#" onClick="alert(document.cookie);">click to see the awesome</a>`; 

仍在工作: – [(正在进行中)

Plunker示例 (Angular 2.0.0-rc-1)

另请参阅Angular 2安全跟踪问题

https://angular.io/docs/ts/latest/api/platform-b​​rowser/index/DomSanitizer-class.html

关于{{...}}提示

无法使用prop="{{sanitizedContent}}"来绑定已消毒的内容,因为{{}}会在分配值破坏清理之前对其进行绑定。