Angular2 innerHtml 绑定删除样式属性

我的问题是,当我使用 innerHtml binding-angular2时,会删除所有的 style 属性。这对我来说很重要,因为在我的 Task-html 中,所有样式都是在服务器端生成的。 例如:

@Component({
selector: 'my-app',
template: `
<input type="text" [(ngModel)]="html">
<div [innerHtml]="html">
</div>
`,
})
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=preview

谢谢!

75234 次浏览

You can leverage DomSanitized to avoid it.

The easiest way is to create custom pipe like:

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);
}
}

So you can use it like:

<div [innerHtml]="html | safeHtml"></div>

Plunker Example

I improved the example of yurzui a bit by completing the needed imports:

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);
}
}

I also had to add the class in my app.module.ts file

import ...
import {SafeHtmlPipe} from "./pipes/safehtml.pipe";
@NgModule({
declarations: [
AppComponent,
...,
SafeHtmlPipe  <--
],
imports: [...],
providers: [...],
bootstrap: [AppComponent]
})
export class AppModule {
}

Note that the sanitizer has a few methods for trusting content e.g.

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

via https://stackoverflow.com/a/41089093/142714

So, bypassSecurityTrustStyle may also be what you want here, as this will show inline styles within your HTML content (value).

[1] docs: https://angular.io/api/platform-browser/DomSanitizer