【发布时间】:2018-01-12 23:26:43
【问题描述】:
我正在构建一个小型参考应用程序,以了解如何在一个组件中动态注入组件以查看页面上的内容。我收到指向 ViewContainerRef 对象的错误。
这是应该在视图中显示注入组件内容的组件,但它会抛出错误:
这是引发错误的 StatsComponent:
export class StatsComponent implements AfterViewInit, OnDestroy {
@Input() dynComp: DynamicComponent;
@ViewChild(ComponentHostDirective) appComponentHost: ComponentHostDirective;
componentRef: ComponentRef<any>;
constructor(private componentFactoryResolver: ComponentFactoryResolver) { }
ngAfterViewInit() {
this.loadComponent();
}
ngOnDestroy() {
this.componentRef.destroy();
}
loadComponent() {
console.log('inside stats component: ', this.dynComp);
const comp = this.dynComp;
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(comp.component);
console.log('host: ', this.appComponentHost); // <-- this is undefined
const viewContainerRef = this.appComponentHost.viewContainerRef;
viewContainerRef.clear();
this.componentRef = viewContainerRef.createComponent(componentFactory);
(<DynamicComponent>this.componentRef.instance).data = comp.data;
}
}
为什么容器没有被引用?
[更新]:现在可以了!转到我的演示和 github 项目,看看它的实际效果。
【问题讨论】:
-
可能是因为
<ng-template>。尝试使用<div>作为测试。
标签: angular dynamic components