Injecting ngControl in custom validator directive, causes cyclic dependency

给你一囗甜甜゛ 提交于 2021-02-18 20:41:26

问题


i'm trying to create custom angular 2 validator directive, which inject NgControl like this :

@Directive({
  selector: '[ngModel][customValidator]',
  providers: [{provide: NG_VALIDATORS, useExisting: CustomValidatorDirective, multi: true}]
})
export class CustomValidatorDirective implements Validator {
  private validateFunction: ValidatorFn;

  constructor(private control: NgControl) { };

}

But i get the following error:

Cannot instantiate cyclic dependency! NgControl

Does anyone know how i can workarround it, so i can access the ngControl after intialization?


回答1:


Providers, Pipes, Directives declaration are removed from @Component or @Directive decorators after RC6 or RC7. So you just need to remove

providers: [{provide: NG_VALIDATORS, useExisting: CustomValidatorDirective, multi: true}] 

from directive

and add it into @NgModule({}) decorator

@NgModule({
 ...
 providers: [{provide: NG_VALIDATORS, useExisting: CustomValidatorDirective, multi: true}]

})



回答2:


You can inject NgControl via Injector to avoid cyclic dependency.

constructor(private _injector: Injector) { }

ngOnInit() {
  console.log(this._injector.get(NgControl))
}


来源:https://stackoverflow.com/questions/39809084/injecting-ngcontrol-in-custom-validator-directive-causes-cyclic-dependency

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!