Let's consider a scenario where an Angular 2 component-directive needs to dynamically determine the injected dependency it uses based on an @Input().
For example, I would like to be able to specify
<trendy-directive use="'serviceA'">
and have that particular instance of TrendyDirective utilize serviceA. Alternatively, I could specify `'serviceB'` to make it use serviceB instead. (Note: this is a simplified version of my actual objective)
If you believe this approach is flawed, I welcome your feedback along with an explanation.
Here is a basic implementation to illustrate my concept. Assume ServiceA and ServiceB are injectable classes that both implement iService with a method 'superCoolFunction'.
@Component({
selector: 'trendy-directive',
...
})
export class TrendyDirective implements OnInit {
constructor(
private serviceA: ServiceA,
private serviceB: ServiceB){}
private service: iService;
@Input() use: string;
ngOnInit() {
switch (this.use){
case 'serviceA': this.service = this.serviceA; break;
case 'serviceB': this.service = this.serviceB; break;
default: throw "There's no such thing as a " + this.use + '!';
}
this.service.superCoolFunction();
}
}
While this solution may technically function, there could be more efficient methods for achieving dynamic dependency injection.