使用angular2为innerHtml渲染CSS
发布时间:2020-12-17 10:16:44 所属栏目:安全 来源:网络整理
导读:我正在尝试使用inner HTML和我从SQL获得的html css字符串来呈现HTML模板. 模板字符串示例: html xmlns="http://www.w3.org/1999/xhtml" headtitleTemplate Name/titlestyle type="text/css" p{ color:red; }/style /head body h1#headding#/h1 p style="col
我正在尝试使用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://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>`; } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |