关于angular:Angular2 innerHtml绑定删除样式属性

Angular2 innerHtml binding remove style attribute

本问题已经有最佳答案,请猛点这里访问。

我的问题是,当我使用innerHTML绑定时,angular2会删除所有样式属性。这对我很重要,因为在我的任务中——HTML是在服务器端以所有样式生成的。例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Component({
  selector: 'my-app',
  template: `
    <input type="text" [(ngModel)]="html">
   
   
  `,
})
export class App {
  name:string;
  html: string;
  constructor() {
    this.name = 'Angular2'
    this.html ="<span style="color:red;">1234</span>";
  }
}

但在dom中,我只看到1234,而这个文本不是红色的。

http://plnkr.co/edit/uqjofmkl9owmrij38u8d?P=预览

谢谢您!


你可以利用DomSanitized来避免它。

最简单的方法是创建自定义管道,如:

1
2
3
4
5
6
7
8
9
10
import { DomSanitizer } from '@angular/platform-browser'
import { PipeTransform, Pipe } from"@angular/core";

@Pipe({ name: 'safeHtml'})
export class SafeHtmlPipe implements PipeTransform  {
  constructor(private sanitized: DomSanitizer) {}
  transform(value) {
    return this.sanitized.bypassSecurityTrustHtml(value);
  }
}

所以你可以像这样使用它:

1
 

柱塞实例


我通过完成所需的导入对yurzui的示例进行了一些改进:

1
2
3
4
5
6
7
8
9
10
import {DomSanitizer} from '@angular/platform-browser';
import {PipeTransform, Pipe} from"@angular/core";

@Pipe({ name: 'safeHtml'})
export class SafeHtmlPipe implements PipeTransform  {
  constructor(private sanitized: DomSanitizer) {}
  transform(value) {
    return this.sanitized.bypassSecurityTrustHtml(value);
  }
}

我还必须在app.module.ts文件中添加该类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import ...
import {SafeHtmlPipe} from"./pipes/safehtml.pipe";
@NgModule({
    declarations: [
        AppComponent,
        ...,
        SafeHtmlPipe  <--
    ],
    imports: [...],
    providers: [...],
    bootstrap: [AppComponent]
})
export class AppModule {
}


注意,sanitizer有一些信任内容的方法,例如

1
2
3
return this.sanitizer.bypassSecurityTrustStyle(value);
return this.sanitizer.bypassSecurityTrustHtml(value);
return this.sanitizer.bypassSecurityTrustXxx(value); // - see docs [1]

通过https://stackoverflow.com/a/41089093/142714

因此,bypassSecurityTrustStyle也可能是您在这里想要的,因为这将显示HTML内容(value)中的内联样式。

[1]文档:https://angular.io/docs/ts/latest/api/platform-browser/index/domSanitizer-class.html


Angular2的目标是更具声明性的方法,因此通常不鼓励直接操作HTML。

我相信(几乎)所有HTML操作都是通过Angular的DOM清理进行过滤的。可以想象,对于SPAN元素,style属性没有白名单,实际上,SPAN目前没有允许的属性。