1

我正在一個應用程序,我從服務器以html格式獲取響應。 我正在使用DomSanitizer的bypassSecurityTrustHtml並將清理過的html添加到我的組件()中。Angular 2:我如何應用指令消毒html/innerhtml

我的問題是,一些在響應元素包含標記,以表明鏈接可以從元素如被buildt:

<div thisIsActuallyaLink linkParam1="foo" linkParam2="bar">clickHere</div> 

我想創建一個應用到innerHTML的一個指令,但雖然html顯示,它不是編譯與我的指示...

如果有人想知道爲什麼轉換html沒有完成serverside:響應用於多個應用程序和鏈接必須有不同的相對URL取決於應用: - (

+1

這對於[[innerHTML] =「...」'根本不可能。您可以在運行時編譯組件以獲取動態HTML的組件和指令https://stackoverflow.com/questions/38888008/how-can-i-use-create-dynamic-template-to-compile-dynamic-component-with- angular –

+0

我需要AoT編譯用於我的項目。動態組件看起來很有前途,但我猜測它不適用於AoT? 現在我決定解析html並在'ngAfterViewInit()'期間將標籤轉換爲普通鏈接(丟失routerLinks的單頁功能)。 – clearfix

+0

我不知道目前的狀態。幾個月前是一個關於這個問題的討論,它看起來有辦法讓它一起工作。不確定自那時以來是否改善/惡化。討論是在Angular Github的問題。 –

回答

0

也許嘗試用管,就像這樣:

import { Pipe, PipeTransform } from '@angular/core'; 
import { DomSanitizer } from '@angular/platform-browser'; 

@Pipe({ name: 'safeHTML' }) 
export class SafeHtml implements PipeTransform { 

    constructor(private sanitizer: DomSanitizer) { } 

    transform(html: string) { 
     return this.sanitizer.bypassSecurityTrustHtml(html) 
    } 
} 

,比 [innerHtml]="htmlExample | safeHTML"

+0

這就是domsanitizer的工作原理。它與我已經在做的類似,但是它在編譯期間不使用角度指令(如routerLink),所以這不能解決我的問題。 – clearfix