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