如何将父组件服务注入Angular中的动态组件?

时间:2019-09-03 14:09:21

标签: angular angular-dynamic-components angular-dependency-injection

我正在使用Angular 8,并且已经动态创建了组件。我将服务的父组件放入provider数组。如何将父MyService的同一实例注入动态组件?没有动态组件,我可以通过将服务注入到子组件的构造函数中来实现。但是如何使用动态组件呢?这是创建动态组件的代码

@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 个答案:

答案 0 :(得分:0)

问题出在以下几行:

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

我从头开始创建了一个动态组件注入器。因此,它对父注入器一无所知。结果-不知道父提供者。 我需要做的-将parent参数添加到Injector.create函数中:

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

this.injector注入到父组件的构造函数中:

constructor(private injector: Injector) {
}