Home > other >  Access dynamically loaded child component instance
Access dynamically loaded child component instance

Time:11-22

@ViewChild(ComponentType) comp!: ComponentType;

ngAfterViewInit() {
  console.log('ComponentType instance', comp);
}

To get hold of a child component's instance, I know that ViewChild can be used as shown above. It works for statically added components, but if I use it on a dynamically added component as demonstrated here on StackBlitz, I get undefined on ngAfterViewInit.

What's the proper way to get hold of a dynamically loaded child component's instance?

CodePudding user response:

This is not possible. Angular doesn't get children created dynamically with ViewChild/ViewChildren. See https://github.com/angular/angular/issues/45771 and https://stackoverflow.com/a/43957857/4472932.

But you can save the created childs in a service as example. The component self is const componentRef = viewContainerRef.createComponent<AdComponent>(adItem.component); the componentRef. So a children of ViewChildren/ViewChild is the same like componentRef.

Greetings, Flo

  • Related