2

I am using Angular 8 and I have dynamically created component. I have parent component with the service into providers array. How I can inject the same instance of parent MyService into a dynamic component? Without dynamic component I can achieve it just by injecting into the constructor of the child component that service. But how I can do it with dynamic component? Here is the code of creating dynamic component

@Component({
    selector: 'app-parent',
    templateUrl: './parent.component.html',
    providers: [MyService],
})
export class ParentComponent {
    constructor(
        private componentFactoryResolver: ComponentFactoryResolver,
        private myService: MyService,
    ) {
    }

    createDynamicComponent() {
        const injector: Injector = Injector.create({
            providers: [
                {
                    provide: MAT_DATE_FORMATS,
                    useValue: getMatDateFormat(this.dateFormat),
                },
            ],
        })
        this.dynamicPlaceholder.clear()
        const componentFactory = this.componentFactoryResolver
            .resolveComponentFactory(DynamicComponent)
        const componentRef = this.dynamicPlaceholder
            .createComponent(componentFactory, 0, injector)
    }
}

1 Answer 1

2

The problem was in these lines:

const injector: Injector = Injector.create({
      providers: [
         {
            provide: MAT_DATE_FORMATS,
            useValue: getMatDateFormat(this.dateFormat),
         },
      ],
})

I created a dynamic component injector from scratch. So it didn't know anything about parent injector. As a result - don't know about parent providers. All I need to do - is add parent parameter to the Injector.create function:

const injector: Injector = Injector.create({
          providers: [
             {
                provide: MAT_DATE_FORMATS,
                useValue: getMatDateFormat(this.dateFormat),
             },
          ],
          parent: this.injector
})

Where this.injector is injected into the constructor of the parent component:

constructor(private injector: Injector) {
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.