angular – 无法读取未定义的属性’viewContainerRef’

前端之家收集整理的这篇文章主要介绍了angular – 无法读取未定义的属性’viewContainerRef’前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
@H_403_3@
我试图在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>在模板中

@H_502_24@解决方法
你可以采取这种方法
不要创建指令,而是提供一个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();
}
@H_403_3@

猜你在找的Angularjs相关文章