0

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!

John F.
  • 67
  • 1
  • 1
  • 6
  • 2
    ViewChild, only get the "children" of a component -it's **not** like the document.getElementByClass of javaScript-, re-think your code using services or similar – Eliseo Jul 12 '21 at 06:37
  • 1
    Eliseo is totally correct. The issue has basically been dealt with in https://stackoverflow.com/questions/36614284/what-is-viewchild-in-angular2, https://blog.angular-university.io/angular-viewchild/, https://www.digitalocean.com/community/tutorials/angular-viewchild-access-component. Basically you'll have to reapply your solution in each component, maybe have a basecomponent that takes this solution from which you can inherit. (extends from) – qqtf Jul 12 '21 at 08:14

0 Answers0