无法读取未定义的属性“viewContainerRef" [英] Cannot read property 'viewContainerRef' of undefined

查看:37
本文介绍了无法读取未定义的属性“viewContainerRef"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试显示与 angular 文档中的示例相似(不精确)的动态组件.

I am trying to display a dynamic component similar (not exact) to the example in angular docs.

我有一个带有 viewContainerRef 的动态指令

I have a dynamic directive with 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);
}

终于在模板中添加了

Finally added <ng-template dynamicComponent></ng-template> in template

推荐答案

您可以采用以下方法:不要创建指令,而是给 ng-template

You can take this approach: don't create directive, instead give an Id to ng-template

<ng-template #dynamicComponent></ng-template>

在组件类中使用 @ViewChild 装饰器

use @ViewChild decorator inside your component class

@ViewChild('dynamicComponent', { read: ViewContainerRef }) myRef

ngAfterViewInit() {
    const factory = this.componentFactoryResolver.resolveComponentFactory(component);
    const ref = this.myRef.createComponent(factory);
    ref.changeDetectorRef.detectChanges();
}

这篇关于无法读取未定义的属性“viewContainerRef"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆