问题描述
我正在尝试在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);
}
}
但是由于未知原因,视图为undefined
我在这里做错了什么?
解决方法
您可以采用这种方法:不要创建指令,而是给ng-template
提供一个ID
<ng-template #dynamicComponent></ng-template>
在组件类中使用@ViewChild
装饰器
@ViewChild('dynamicComponent',{ read: ViewContainerRef }) myRef
ngAfterViewInit() {
const factory = this.componentFactoryResolver.resolveComponentFactory(component);
const ref = this.myRef.createComponent(factory);
ref.changeDetectorRef.detectChanges();
}
希望您可以在您的方法中应用它。
,将static
的值更改为false
是可行的。
@ViewChild('unsubscribeDisclaimer',{ read: ViewContainerRef,static: false }) unsubscribeDisclaimer: ViewContainerRef;