Angular 16 - How to Efficiently Handle Dynamic Component Creation with Dependency Injection?
I've been researching this but I need help solving I'm working on a personal project and I'm currently working on an Angular 16 application where I need to dynamically create components at runtime based on user input... I understand that Angular's `ComponentFactoryResolver` is typically used for this, but I'm facing issues with dependency injection for the dynamically created components. When I try to inject a service into my dynamically created component, it seems to be using the wrong injector context. I've set up a base dynamic component like this: ```typescript import { Component, Input, Injector } from '@angular/core'; import { MyService } from './my.service'; @Component({ selector: 'dynamic-component', template: `<div>Hello, {{name}}!</div>` }) export class DynamicComponent { @Input() name: string; constructor(private myService: MyService) { console.log(this.myService.getData()); // This returns undefined } } ``` Then, in my main component, I create the dynamic component like this: ```typescript import { Component, ViewChild, ViewContainerRef, ComponentFactoryResolver } from '@angular/core'; import { DynamicComponent } from './dynamic.component'; @Component({ selector: 'app-root', template: `<ng-container #dynamicContainer></ng-container>` }) export class AppComponent { @ViewChild('dynamicContainer', { read: ViewContainerRef }) dynamicContainer: ViewContainerRef; constructor(private componentFactoryResolver: ComponentFactoryResolver, private injector: Injector) {} createComponent() { const factory = this.componentFactoryResolver.resolveComponentFactory(DynamicComponent); const componentRef = this.dynamicContainer.createComponent(factory, null, this.injector); componentRef.instance.name = 'World'; } } ``` The issue arises when the `DynamicComponent` tries to use the injected `MyService`. It consistently logs `undefined` instead of the expected data. I've tried using both `Injector.get(MyService)` in the constructor as well as injecting it directly via the injector provided in `createComponent`, but neither seems to work. I've also made sure that `MyService` is provided in a shared module so that it can be accessed by all components. Here's what my service looks like: ```typescript import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class MyService { getData() { return 'Data from MyService!'; } } ``` I've read various articles and documentation but haven't found a clear solution to ensure that the service is properly injected into dynamically created components. Any insights or suggestions would be greatly appreciated! Has anyone else encountered this? I'm working in a Windows 10 environment. Hoping someone can shed some light on this. This is happening in both development and production on Debian.