2016-10-10 63 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解釋添加 –