css - ngclass - ng-deep用法



在RC.1中,使用绑定语法无法添加某些样式 (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);
  }
}

另请参见 https://angular.io/api/platform-browser/DomSanitizer

<div [innerHTML]="someHtml | safeHtml"

更新

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

原版的

这应该在RC.2中修复

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

Angular2引入了CSS值和属性绑定的清理,如RC.1中的 [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(...);

}

并绑定到此值而不是不受信任的普通字符串。

这也可以用管子包裹

@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-browser/index/DomSanitizer-class.html

关于 {{...}} 提示

使用 prop="{{sanitizedContent}}" 无法绑定已清理的内容,因为 {{}} 会在分配之前对其进行字符串化,从而中断清理。

https://src-bin.com

风格如

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

不再添加





angular