Cannot read property 'viewContainerRef' of undefined
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 }) myRefngAfterViewInit() { const factory = this.componentFactoryResolver.resolveComponentFactory(component); const ref = this.myRef.createComponent(factory); ref.changeDetectorRef.detectChanges();}
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]})
In Angular 8 my fix was:
@ViewChild('dynamicComponent', {static: true, read: ViewContainerRef}) container: ViewContainerRef;