Choose injector when creating components
See original GitHub issue🚀 feature request
Relevant Package
Description
Often, I’d like to inject different values into different components. For example, have a component tree with color: 'BLUE
injected, and another component tree with color: 'RED'
injected.
This sort of desire comes up in a lot of different forms. Sometimes the component tree exist contemporaneously; other times they don’t (e.g. router-like functionality).
The point of dependency injection is to not code against fixed values, however Angular’s DI currently makes it cumbersome to adjust the injector.
Describe the solution you’d like
Specify the injector when creating the component. Example syntax:
export class RootComponent {
constructor(private readonly injector: Injector) {}
readonly blueProviders: StaticProviders[] = [{ provide: COLOR, useValue: 'BLUE' }];
readonly blueInjector = Injector.create(this.blueProviders, this.injector);
}
<my-component [@injector]="blueInjector"></my-component>
or
<my-component [@providers]="blueProviders"></my-component>
Describe alternatives you’ve considered
-
Inject an
Observable
. However that complicates client code, and requires components to understand how to handle changes. -
Use non-template code to dynamically create components. However, lifecycles methods, etc. make the approach complex in general.
-
Use
*ngComponentOutlet
. However, like (2), that removes the ability to use inputs with the child component, and it requires explicitly adding components to module entry points.
Issue Analytics
- State:
- Created 3 years ago
- Reactions:3
- Comments:15 (11 by maintainers)
Top GitHub Comments
A solution that allows injection of dynamic view values (doesn’t allow specifying the Injector, but can inject values). It does not create DOM noise.
The
exampleValue
directive would be superfluous if it were not for the feature regression in Angular 4 (#15998) where template directives aren’t DI parents for the template.Full example
https://stackblitz.com/edit/angular-25tawh
@djleonskennedy A wrapping component creates DOM noise and CSS burden, though, and making it dynamic to have something like
doesn’t work since
use-injector
has to statically define its providers and cannot reference them from an input. So you’d have to create different wrapper components for every injector, which then becomes problematic if you build your injector somewhat dynamically as well (which I think is what @pauldraper wants to do).My first thought here was a structural directive like
But this actually turns out not to really lead anywhere either.
Edit: The above confuses injectors and providers a bit, but I think it’s still clear enough. In the end these are separate issues for injectors and providers since wrapping components can define providers, but not injectors for their content.