2017-08-03 69 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