我正在尝试使用inner
HTML和我从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>
现在它渲染HTML很好但看起来它会删除样式标记并只在其中呈现文本.
渲染示例:
HTML渲染部分:
<div [innerHtml]="templateBody"> </div>
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 }
我已经尝试了封装:ViewEncapsulation.Emulated / None等,尝试了内联CSS,我尝试附加:host>>>面前的p标签.他们都呈现相同.
有什么建议?
与DomSanitizer一起使用bypassSecurityTrustHtml和SafeHtml,如下所示,
原文链接:https://www.f2er.com/angularjs/240376.html演示: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>`; } }