CodexBloom - Programming Q&A Platform

Angular 15: Difficulty with Dynamic Component Loading Leading to Injection Errors

👀 Views: 53 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-12
angular dynamic-loading dependency-injection TypeScript

I've searched everywhere and can't find a clear answer. I'm facing a challenge with dynamically loading components in Angular 15. I have a scenario where I need to load a component based on user interactions, and I'm using `ComponentFactoryResolver` for this purpose. However, I'm running into an injection error when trying to resolve services in the dynamically loaded component. The error states: `No provider for MyService!`. Here's the code snippet for the dynamic component loader: ```typescript import { Component, ComponentFactoryResolver, Injector, ViewChild, ViewContainerRef } from '@angular/core'; import { MyService } from './my.service'; import { DynamicComponent } from './dynamic.component'; @Component({ selector: 'app-host', template: `<ng-template #dynamicContainer></ng-template>` }) export class HostComponent { @ViewChild('dynamicContainer', { read: ViewContainerRef, static: true }) container!: ViewContainerRef; constructor(private resolver: ComponentFactoryResolver, private injector: Injector) {} loadComponent() { const factory = this.resolver.resolveComponentFactory(DynamicComponent); const componentRef = this.container.createComponent(factory, 0, this.injector); } } ``` My `DynamicComponent` looks like this: ```typescript import { Component, OnInit } from '@angular/core'; import { MyService } from './my.service'; @Component({ selector: 'app-dynamic', template: `<p>Dynamic Component Loaded!</p>` }) export class DynamicComponent implements OnInit { constructor(private myService: MyService) {} ngOnInit() { console.log('Service Initialized', this.myService); } } ``` I've tried injecting `MyService` using the `Injector` from the `HostComponent`, but I still encounter the same error. I also attempted to provide the service in the `@NgModule` of the `DynamicComponent`, but this approach didn't resolve the issue either. What could I be missing here? How can I ensure that my dynamically loaded component has access to its required services? Any guidance would be appreciated!