像
<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(html); // return this.sanitizer.bypassSecurityTrustHtml(html); // return this.sanitizer.bypassSecurityTrustScript(html); // return this.sanitizer.bypassSecurityTrustUrl(html); // return this.sanitizer.bypassSecurityTrustResourceUrl(html); } } <div [innerHTML]="someHtml | safeHtml"
更新
DomSanitizationService将DomSanitizer在RC.6中重命名为
DomSanitizationService
DomSanitizer
原版的
Angular2 intruduced CSS值的消毒和财产样结合[innerHTML]=...,并[src]="..."在RC.1
[innerHTML]=...
[src]="..."
这些值可以通过使用标记为受信任 DomSanitizer.bypassSecurityTrustStyle(...)
DomSanitizer.bypassSecurityTrustStyle(...)
import {DomSanitizer} from '@angular/platform-browser'; ... constructor(sanitizer: DomSanitizationService) { this.backgroundImageStyle = sanitizer.bypassSecurityTrustStyle('url(' + this.image + ')'); // for HTML // this.backgroundImageStyle = sanitizer.bypassSecurityTrustHtml(...); }
并绑定到该值,而不是不受信任的纯字符串。
这也可以包裹在类似
@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>`;
提示{{...}}
{{...}}
无法使用已清理的内容,prop="{{sanitizedContent}}"因为{{}}在分配值之前,stringyfies值会破坏清理。
prop="{{sanitizedContent}}"
{{}}