我正在使用 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)
}
}