使用angular2为innerHtml渲染CSS

Sha*_*ald 7 innerhtml angular

我试图使用innerHTML和我从SQL获得的html + css字符串呈现HTML模板.

模板字符串示例:

<html xmlns="http://www.w3.org/1999/xhtml"> <head><title>Template Name</title><style type="text/css"> p{ color:red; }</style> </head> <body> <h1>#headding#</h1> <p style="color:red;">#paragraph#</p><a href="#url#">#urltext#</a> </body> </html>
Run Code Online (Sandbox Code Playgroud)

现在它渲染HTML很好但看起来它会删除样式标记并只在其中呈现文本.

渲染示例:

在此输入图像描述

HTML渲染部分:

<div [innerHtml]="templateBody">
</div>
Run Code Online (Sandbox Code Playgroud)

Home.component.ts部分:

@Component({
    selector: "home",
    templateUrl: `client/modules/home/home.component.html`,
    encapsulation: ViewEncapsulation.Emulated
})
export class HomeComponent implements OnInit{
    templateBody: string;
.....other code
}
Run Code Online (Sandbox Code Playgroud)

我已经尝试了封装:ViewEncapsulation.Emulated/None等,尝试了内联CSS,我尝试附加:host >>> inf标签.他们都呈现相同.

有什么建议?

mic*_*yks 6

DomSanitizer一起使用bypassSecurityTrustHtml和SafeHtml,如下所示,

演示:https://plnkr.co/edit/eBlzrIyAl0Il1snu6WJB? p =preview

import { DomSanitizer } from '@angular/platform-browser'

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

@Component({
  selector: 'my-app',
  template: `

      <div  [innerHtml]="html | safeHtml"></div>
  `,
})
export class App {
  name:string;
  html: safeHtml;
  constructor() {
    this.name = 'Angular2'
    this.html = `<html xmlns="http://www.w3.org/1999/xhtml"> <head><title>Template Name</title><style type="text/css"> p{ color:red; }</style> </head> <body> <h1>#headding#</h1> <p style="color:red;">#paragraph#</p><a href="#url#">#urltext#</a> </body> </html>`;
  }

}
Run Code Online (Sandbox Code Playgroud)