【发布时间】:2021-02-18 08:19:16
【问题描述】:
我正在尝试在内部动态加载组件,unsubscribeDisclaimer。
下面是我的HTML
<ng-template #TooltipInfo>
<p #unsubscribeDisclaimer></p>
</ng-template>
在 Component.ts 中
@ViewChild('unsubscribeDisclaimer', { read: ViewContainerRef, static: true }) unsubscribeDisclaimer: ViewContainerRef;
this.createComponent(unsubscribeDisclaimer, this.unsubscribeDisclaimer);
createComponent (content, view: ViewContainerRef) {
console.log(view);
const componentType = this.contentMappings[content.type];
if(view) {
this.componentFactory = this.componentFactoryResolver.resolveComponentFactory(componentType);
this.componentReference = view.createComponent(this.componentFactory);
this.componentReference.instance.contentOnCreate(content);
}
}
但不知什么原因,view是undefined
我在这里做错了什么?
【问题讨论】:
-
您在组件生命周期的哪个时间点调用
this.createComponent?只有在ngAfterViewInit之后才能访问模板视图。所以如果这个方法在这个钩子之前被调用,它将是未定义的。试着把你的电话移到这个钩子里。 -
我厌倦了 ngOnInit 和 ngAfterViewInit,即使设置了超时
标签: angular typescript angular-dynamic-components