1

我正在使用 Angular 8,并且我已经动态创建了组件。我将带有服务的父组件放入提供者数组中。如何将相同的父实例注入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)
    }
}
4

1 回答 1

1

问题出在以下几行:

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) {
}
于 2019-09-04T08:08:21.277 回答