Angular 2 dynamic dependency injection based on @Input() Angular 2 dynamic dependency injection based on @Input() typescript typescript

Angular 2 dynamic dependency injection based on @Input()


It is

// can be a service also for overriding and testingexport const trendyServiceMap = {  serviceA: ServiceA,  serviceB: ServiceB}constructor(private injector: Injector) {}    ...ngOnInit() {    if (trendyServiceMap.hasOwnProperty(this.use)) {        this.service = this.injector.get<any>(trendyServiceMap[this.use]);    } else {        throw new Error(`There's no such thing as '${this.use}'`);    }}


In general, same approach is described in Angular2 documentation: InjectorComponent

@Component({    providers: [Car, Engine, Tires, heroServiceProvider, Logger]})export class InjectorComponent {     car: Car = this.injector.get(Car);     heroService: HeroService = this.injector.get(HeroService);     hero: Hero = this.heroService.getHeroes()[0];     constructor(private injector: Injector) { }}

You must inject Injector in constructor and list all services in providers property of @Component annotation. Then you can injector.get(type), where type will be resolved from your @Input. As per documentation, Service is not actually injected until you ask for it (.get()).


There is a service named Inject in @angular/core module. With @Inject you can achieve alternative way of injection. But that can be done only in constructor.

So you will need to put component's inputs in the inputs array of your @component decorator (do not use @Input decorator inside class) and then inject that input variable in constructor.