Cannot read property 'viewContainerRef' of undefined

前端 未结 8 781
鱼传尺愫
鱼传尺愫 2021-01-01 13:50

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

I have a dynamic directive with viewContainerRef

@Dire         


        
8条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-01 14:16

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

    
    

    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();
    }
    

提交回复
热议问题