Simple case but could not figure out the answer so far.
From angular v4 when trying to manually inject NgControl
:
this.injector.get(NgControl);
The lint starts complaining:
get is deprecated: from v4.0.0 use Type<T> or InjectionToken<T>
How to properly inject it using injector ?
(Using Angular 8) This passes without TSLint
errors:
this.injector.get<NgControl>(NgControl as Type<NgControl>);
However there is a more elegant solution via the constructor.
constructor(@Self() @Optional() public ngControl: NgControl) {
if(this.ngControl) {
this.ngControl.valueAccessor = this;
}
}
But you need to bear in mind this is an inline (more elegant) replacement for NG_VALUE_ACCESSOR
- you will get a cyclical dependency error using both.
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => FieldComponent),
multi: true
}
You have to use it like this now:
this.injector.get<NgControl>(NgControl);
See the angular documention: https://angular.io/api/core/Injector
get<T>(token: Type<T> | InjectionToken<T>, notFoundValue?: T, flags?: InjectFlags): T
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.