CodexBloom - Programming Q&A Platform

Angular 16 - Dynamic Component Loading with Lazy-loaded Modules Causing Injection Issues

👀 Views: 50 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-03
angular dynamic-loading lazy-loading typescript

After trying multiple solutions online, I still can't figure this out. I'm working with an scenario while trying to dynamically load components that are part of a lazy-loaded module in Angular 16. I have a service that triggers the loading of a component, but I'm getting the following behavior: `NullInjectorError: No provider for MyComponent`. Here's the setup: I have a lazy-loaded module `MyLazyModule` that declares and exports `MyComponent`. In my main module, I have a service `DynamicComponentService` that attempts to inject `MyComponent` when creating it dynamically. I've tried several approaches to resolve this, including adding `MyComponent` to the providers array in `MyLazyModule`, but it didn't solve the scenario. Here's a simplified version of my code: ```typescript // my-lazy.module.ts @NgModule({ declarations: [MyComponent], exports: [MyComponent], }) export class MyLazyModule {} // dynamic-component.service.ts @Injectable({ providedIn: 'root' }) export class DynamicComponentService { constructor(private injector: Injector) {} createComponent() { const componentFactory = this.injector.get(ComponentFactoryResolver) .resolveComponentFactory(MyComponent); const componentRef = componentFactory.create(this.injector); return componentRef; } } ``` When I try to load `MyComponent` through `DynamicComponentService`, it fails with the behavior above. I've also attempted to import `MyLazyModule` directly in my main module and tried to use `Injector.fromModule(MyLazyModule)`, but that doesn't seem to work either. Is there a recommended approach for dynamically loading components from lazy-loaded modules in Angular 16? Any insights would be appreciated! How would you solve this?