一尘不染

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

css

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

不再添加


阅读 314

收藏
2020-05-16

共1个答案

一尘不染

更新(最终版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"

更新

DomSanitizationServiceDomSanitizer在RC.6中重命名为

原版的

Angular2 intruduced CSS值的消毒和财产样结合[innerHTML]=...,并[src]="..."在RC.1

这些值可以通过使用标记为受信任 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值会破坏清理。

2020-05-16