I use in Angular the following in order to create a dynamic component:
@Directive({
selector: '[appAdHost]'
})
export class AdHostDirective {
constructor(public viewContainerRef:ViewContainerRef) { }
}
ad.directive.ts is in the app.module. I call it like this from component a (module a):
@ViewChild(AdHostDirective) dlHost: AdHostDirective;
constructor(private cfr: ComponentFactoryResolver) {
}
ngAfterViewInit() {
this.dlHost.viewContainerRef.createComponent(
this.cfr.resolveComponentFactory(DyTwoComponent)
);
}
In component a.component.html I have added
<ng-template adHost></ng-template>
With this configuration everything works as expected. If I move
<ng-template adHost></ng-template>
outside of component a, to another component.html (in the same module or outside of the module) the
@ViewChild(AdHostDirective) dlHost: AdHostDirective;
returns undefined in the console.
ERROR TypeError: can't access property "viewContainerRef", this.adHost is undefined
The structure of the project s as follows:
app.moodule
a.module
b.module
My wish is to be able to call the @ViewChild from a child module (a or b) but to have the template in the root module (app.module). I would be grateful if you could help me with some ideas how to achieve this. Thank you!