Cannot read property 'viewContainerRef' of undefined

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

    In my case, it was Angular 9 and the directive's selector was inside *ngIf. The solution I used was:

    @ViewChild(ExampleDirective, {static: false}) exampleDirectiveHost: ExampleDirective;
    

    Mark static is false due to reasons defined here Angular documentation

    The other thing I did was use

    ngAfterViewInit(){
       const viewContainerRef = this.exampleDirectiveHost.viewContainerRef;;
    }
    
    0 讨论(0)
  • 2021-01-01 14:32

    I had the same problem. You have to add the directive into the AppModule:

     @NgModule({
      declarations: [
        AppComponent,
        ...,
        YourDirective,
      ],
      imports: [
       ...
      ],
      providers: [...],
      bootstrap: [AppComponent],
      entryComponents: [components to inject if required]
    })
    
    0 讨论(0)
提交回复
热议问题