使用angular2为innerHtml渲染CSS

前端之家收集整理的这篇文章主要介绍了使用angular2为innerHtml渲染CSS前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试使用inner HTML和我从sql获得的html css字符串来呈现HTML模板.

模板字符串示例:

  1. <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渲染部分:

  1. <div [innerHtml]="templateBody">
  2. </div>

Home.component.ts部分:

  1. @Component({
  2. selector: "home",templateUrl: `client/modules/home/home.component.html`,encapsulation: ViewEncapsulation.Emulated
  3. })
  4. export class HomeComponent implements OnInit{
  5. templateBody: string;
  6. .....other code
  7. }

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

有什么建议?

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

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

  1. import { DomSanitizer } from '@angular/platform-browser'
  2.  
  3. @Pipe({ name: 'safeHtml'})
  4. export class SafeHtmlPipe implements PipeTransform {
  5. constructor(private sanitized: DomSanitizer) {}
  6. transform(value) {
  7. console.log(this.sanitized.bypassSecurityTrustHtml(value))
  8. return this.sanitized.bypassSecurityTrustHtml(value);
  9. }
  10. }
  11.  
  12. @Component({
  13. selector: 'my-app',template: `
  14.  
  15. <div [innerHtml]="html | safeHtml"></div>
  16. `,})
  17. export class App {
  18. name:string;
  19. html: safeHtml;
  20. constructor() {
  21. this.name = 'Angular2'
  22. 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>`;
  23. }
  24.  
  25. }

猜你在找的Angularjs相关文章