Injecting ngControl in custom validator directive, causes cyclic dependency

Krasimir Kirilov picture Krasimir Kirilov · Oct 1, 2016 · Viewed 9.2k times · Source

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?

Answer

Bladito picture Bladito · Jan 11, 2018

You can inject NgControl via Injector to avoid cyclic dependency.

constructor(private _injector: Injector) { }

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