2016-10-10 61 views
6

我想呈现使用innerHTML和我从SQL获得的html + css字符串的HTML模板。使用angular2呈现innerHtml的CSS

模板字符串例如:

<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罚款,但它看起来像它下降的风格标签,只是使得它内部的文本。

enter image description here

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,我试着追加:主机>>> p标签的前面。他们都呈现相同。

有什么建议吗?

回答

4

,如下图所示与bypassSecurityTrustHtml和SafeHtml与DomSanitizer使用它,

DEMO: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>`; 
    } 

} 
+0

感谢,其完美的工作。 –

+0

欢迎@ShaunGroenewald – micronyks

1

我这样做是没有任何管道,只是通过将DomSanitizer和SafeHtml注入我的组件并在我的标记st上运行bypassSecurityTrustHtml环。这使我可以保持我的内联样式不被解析。

import { Component, OnInit } from '@angular/core'; 
import { DomSanitizer, SafeHtml } from '@angular/platform-browser'; 

@Component({ 
    selector: "foo", 
    templateUrl: "./foo.component.html" 
}) 

export class FooComponent { 
    html: SafeHtml; 
    constructor(private sanitizer: DomSanitizer) { 
     this.html = this.sanitizer.bypassSecurityTrustHtml('<span style="color:##0077dd">this works</span>'); 
    } 
} 

和foo.component.html模板

<div [innerHtml]="html"></div> 
+1

此帖被标记为低质量,因为它缺少一个解释。尝试扩展你的答案。 –

+1

@DerekBrown解释添加 –