I am working with Angular reactive forms. In my scenario, validators are added dynamically to my controls.
This is done like follows:
const myControl = myFormGroup.get('myControl');
if (myControl.validator) {
myControl.setValidators([ myControl.validator, Validators.required ]); //preserve existing validators
} else {
myControl.setValidators([ Validators.required ]);
}
This works just fine.
The Problem
I need a way to also remove a specific validator while preserving the others.
myControl.validators only returns a function but not an array of validators which makes it impossible to pick one to remove while leaving the others.
I know there are workarounds like keeping track of the existing validators elswhere, etc.
My question however is: can this be achieved directly on the AbstractControl?
The following issue on Github discusses the problem: https://github.com/angular/angular/issues/13461
The solutions provided there don't seem to work for me, as I am not only having to deal with the required validator but also with numerous custom validators.
Thanks in advance for any hints or solutions to this!
Cheers, Mike
Since there is no elegant solution to this, I have bitten the bullet to write my own RequiredIf validator.
It does two things:
Here's my code of the validator (just as I use it currently, no time to optimize it).
And here's the application on the form:
additionally, you have to call
ValidationSubscriptionCache.unsubscribeAll();in thengOnDestroy()of your component holding the form.Cheers, Mike