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