简体   繁体   中英

How to inject parent component service into dynamic component in Angular?

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)
    }
}

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) {
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM