Krasimir Kirilov
Krasimir Kirilov

Reputation: 535

Injecting ngControl in custom validator directive, causes cyclic dependency

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?

Upvotes: 26

Views: 21483

Answers (3)

Federico Bellini
Federico Bellini

Reputation: 514

Just remove the NG_VALIDATORS from the providers of the @Directive

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

and set the component's validator on the constructor

constructor(public ngControl: NgControl) {
  ngControl.valueAccessor = this;
}

Upvotes: 0

Bladito
Bladito

Reputation: 1209

You can inject NgControl via Injector to avoid cyclic dependency.

constructor(private _injector: Injector) { }

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

Upvotes: 28

micronyks
micronyks

Reputation: 55443

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}]

})

Upvotes: 6

Related Questions