2017-08-03 67 views
0

在我的Angular 4應用程序中,我需要動態創建兩個組件並將它們注入到模板中。我已經用一個組件成功完成了這一工作,但現在我需要添加另一個組件。根據屬性的值選擇元素主機

我有這樣的指令:

import { Directive, ViewContainerRef } from '@angular/core'; 

@Directive({ 
    selector: '[component-host]', 
}) 
export class ComponentHost { 
    constructor(public viewContainerRef: ViewContainerRef) { } 
} 

,我有這樣的HTML模板摘錄:

<!--- HTML ---> 
<ng-template component-host></ng-template> 

ViewChild

// TypeScript 
@ViewChild(ComponentHost) componentHost: ComponentHost; 

這一切的偉大工程,我有一些代碼創建該組件並插入它。但是,現在我需要在同一個模板中動態注入附加組件。目前,我必須分開指令,但這顯然不是最佳解決方案。是否可以使用屬性的值來選擇@ViewChild中的元素?沿着線的東西:

<!--- HTML ---> 
<ng-template component-host='replace1'></ng-template> 
<ng-template component-host='replace2'></ng-template> 

// TypeScript 
// How do I select the element with an attribute with a certain value? 
@ViewChild(ComponentHost) componentHost: ComponentHost; 

我創造我的部件是這樣的:

protected createComponent(componentType: Type<any>, componentHost): any { 
    const componentFactory = this.componentFactoryResolver.resolveComponentFactory(componentType); 
    const viewContainerRef = componentHost.viewContainerRef; 

    viewContainerRef.clear(); 

    const componentRef = viewContainerRef.createComponent(componentFactory); 
    componentRef.changeDetectorRef.detectChanges(); 

    return componentRef.instance; 
} 

這對我來說重要的是能夠給detectChanges()一旦組件已創建。我嘗試了各種排列但沒有工作。有任何想法嗎?

如果我使用散列選擇器,則const viewContainerRef = componentHost.viewContainerRef;返回null。

+0

顯示你的代碼如何插入組件。和爲什麼你使用指令,而不是像這樣的模板引用''''@ViewChild('component-host1',{read:ViewContainerRef})componentHost: ComponentHost; ' –

+0

@Maximus我在https://angular.io/guide/dynamic-component-loader上查看了食譜。我的代碼幾乎完全相同。 – serlingpa

回答

0

目前尚不清楚爲什麼要使用組件來選擇ng-template元素。你可以使用它的模板參考:

<!--- HTML ---> 
<ng-template #component-host-replace1></ng-template> 
<ng-template #component-host-replace2></ng-template> 

// TypeScript 
@ViewChild('component-host-replace1', {read: ViewContainerRef}) host1: ViewContainerRef; 
@ViewChild('component-host-replace2', {read: ViewContainerRef}) host2: ViewContainerRef; 
+0

我在https://angular.io/guide/dynamic-component-loader上關注了食譜。我的代碼幾乎完全相同。我已將我的組件創建代碼添加到我的問題中。 – serlingpa