angular – 无法读取未定义的属性’viewContainerRef’
发布时间:2020-12-17 17:59:24 所属栏目:安全 来源:网络整理
导读:我试图在angular docs中显示一个类似(不完全)的动态组件. 我有一个带有viewContainerRef的动态指令 @Directive({ selector: '[dynamicComponent]'})export class DynamicComponentDirective { constructor(public viewContainerRef: ViewContainerRef) { }}
我试图在angular docs中显示一个类似(不完全)的动态组件.
我有一个带有viewContainerRef的动态指令 @Directive({ selector: '[dynamicComponent]' }) export class DynamicComponentDirective { constructor(public viewContainerRef: ViewContainerRef) { } } 摘自组件代码 @ViewChild(DynamicComponentDirective) adHost: DynamicComponentDirective; .. ngAfterViewInit() { let componentFactory = null; console.log(component); componentFactory = this.componentFactoryResolver.resolveComponentFactory(component); // this.adHost.viewContainerRef.clear(); const viewContainerRef = this.adHost.viewContainerRef; viewContainerRef.createComponent(componentFactory); } 最后添加< ng-template dynamicComponent>< / ng-template>在模板中 解决方法
你可以采取这种方法:
不要创建指令,而是提供一个Id到ng模板 <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(); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |