Detect change of Validators in Angular

Viewed 280

I want to detect a change (add/remove) in control validators. For example, I have a control without any validator, and then I want to add "Validators.required".

this.formGroup = this.fb.group({
    name: [null]
});

// And then, let's say 1 second later, something like this happens:
setTimeout(() => {
  this.formGroup.controls['name'].setValidators(Validators.required);
}, 1000);

In the template:

<input myDirective formControlName="name">

In the directive myDirective I want to detect when the setValidators happen, or more general, I want to know when validators for that control have changed.

In the constructor of myDirective I inject the NgControl so I have access to it:

constructor(private ngControl: NgControl) {
}

But now I cannot see how to achieve that.

  • I have a working solution, using ngDoCheck and this.ngControl.control.validator({} as AbstractControl) to be able to retrieve the validators, and then compare to the original validators, etc. But this is ugly, since this function is executed many times unnecessarily.

  • I have also tried with es6 Proxy (proxying this.ngControl.control) but I had no luck, I am not notified when the validators change.

What is the best way to achieve this? Why is Angular not exposing an Observable for that?


Edit:

I have seen that if I do:

this.formGroup.controls['name'].setValidators(Validators.required);
this.formGroup.controls['name'].updateValueAndValidity();

Then in the myDirective directive I can subscribe to this.ngControl.control.statusChanges, and then compare the old validator(s) with the new validator(s) to see if some have been added/removed, etc.

Still not ideal, because a status change does not mean that validator functions have changed, but a decent solution.

0 Answers
Related