Cannot read property 'viewContainerRef' of undefined

前端 未结 8 710
鱼传尺愫
鱼传尺愫 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:07

    Noted that I face the same problem if directive selector (dynamicComponent in this case) is at :

    1. first element of the component

    2. parent element with *ngIf condition

    Hence, I avoid it by put it inside at non-root tag in the component html & load component to viewContainerRef only when the condition match.

    0 讨论(0)
  • 2021-01-01 14:09

    You see this error when the directive does not construct. You can set a breakpoint on the directive's constructor and check if the breakpoint ever hits. If not, that means that you are not loading the directive correctly. Then you can check that your component that is loading the directive it is properly adding the directive into the template.

    0 讨论(0)
  • 2021-01-01 14:15

    The problem might also be that the selector of the viewRef (dynamicComponent in this example) does not match the one specified in the template of the component which uses the componentFactoryResolver.

    0 讨论(0)
  • 2021-01-01 14:16

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

    <ng-template #dynamicComponent></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();
    }
    
    0 讨论(0)
  • 2021-01-01 14:24

    I ran into this problem as well and the reason was that the location which I wanted to load my component dynamicly into was inside an ng-if that was hidden initially.

    <div *ngIf="items">
       <ng-template appInputHost></ng-template>
    </div>
    
    @ViewChild(InputHostDirective, { static: true }) inputHost: InputHostDirective;
    

    Moving the ng-template to outside the ng-if solved the problem.

    0 讨论(0)
  • 2021-01-01 14:29

    In Angular 8 my fix was:

    @ViewChild('dynamicComponent', {static: true, read: ViewContainerRef}) container: ViewContainerRef;

    0 讨论(0)
提交回复
热议问题