在我的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。
显示你的代码如何插入组件。和为什么你使用指令,而不是像这样的模板引用' ng-template>'''@ViewChild('component-host1',{read:ViewContainerRef})componentHost: ComponentHost; ' –
@Maximus我在https://angular.io/guide/dynamic-component-loader上查看了食谱。我的代码几乎完全相同。 – serlingpa