2017-03-16 50 views
0

我有2個@components說和。現在,我必須動態加載爲innerHTML,例如,如下面Angular 2:在innerHTML中加載動態組件

組件1.HTML

<div [innerHTML]="domEl | safeHtml"></div> 

在Angular2部件-1類

import { 
    Component, 
    OnInit, 
    ViewEncapsulation 
} from '@angular/core'; 


@Component({ 
    selector: 'component-1', 

    templateUrl: './component-1.html', 

    encapsulation: ViewEncapsulation.None 
}) 
export class Component1 implements OnInit {  

    public ngOnInit() { 
    this.domEl = '<component-2 data="1234"></component-2>' 
    } 
} 

組分-2已在app.module.ts文件經由聲明[]注入。另外safeHtml是用於安全HTML轉換的管道。

即使那麼問題是組件-2不加載。任何人都可以建議我如何解決這個問題?

注:

  • ,如果我有分量-2組件1.HTML直接它將工作。但是我們有一個情況是我們不能動態注入組件-2。
  • Stack基於Angular2,TypeScript和Webpack。
+1

不是加載innerHtml,而是使用帶有ngIf或ngSwitch的模板。 – Fals

+0

不能這樣做,在我的情況下,這是行不通的。 –

+0

您不能將組件注入爲html。組件從Shadow Dom渲染到Real Dom。當你使用** innerHTML **注入東西時,它應該是原始的Html,而不是那些需要渲染管道的東西。正如我之前所說的,您必須使用ngIf或ngSwitch – Fals

回答

0

爲了安全起見,Angular不處理傳遞給[innerHTML]="..."的除了消毒之外的HTML。沒有創建綁定,組件,指令等,因爲如上所述,Angular忽略了內容。你可以做的是在運行時創建一個組件,就像在Equivalent of $compile in Angular 2中解釋的那樣。 AFAIR有人建立了一個模塊,使這更容易,但我不記得細節。