I have a FormGroup
defined like below:
this.businessFormGroup: this.fb.group({
'businessType': ['', Validators.required],
'description': ['', Validators.compose([Validators.required, Validators.maxLength(200)])],
'income': ['']
})
Now when businessType
is Other
, I want to remove Validators.required
validator from description
. And if businessType
is not Other
, I want to add back the Validators.required
.
I am using the below code to dynamically add/remove the Validators.required
. However, it clears the existing Validators.maxLength
validator.
if(this.businessFormGroup.get('businessType').value !== 'Other'){
this.businessFormGroup.get('description').validator = <any>Validators.compose([Validators.required]);
} else {
this.businessFormGroup.get('description').clearValidators();
}
this.businessFormGroup.get('description').updateValueAndValidity();
My question is, how can I retain the existing validators when adding/removing the required
validator.
The naive approach would be to set the validators of the control whenever the conditional variable changes. But we can actually do better than that by using some indirection + functional programming.
Consider the existence of a
descriptionIsRequired
getter, that acts as a boolan flag.Ideas:
descriptionIsRequired
as argument and depending on it validates a control against required + maxLength or maxLength.descriptionIsRequired
should be considered.The first point is pretty straight forward to implement:
Notice that this is a self capsulated function.
The second point is a little bit more tricky, but in the end it looks like this:
A small explanation of what is happening:
validator
method returns a functionvalidator
could be considered a factory method: whenever its invoked, returns a new function, more specifically, a new instance of ourdescriptionValidator
using the newestdescriptionIsRequired
value.A live demo in the following stackblitz
This one work for me
Maybe this helps:
Adding Validators.required to the validatorset of an existing
AbstractControl
:Angular forms have a built in function setValidators() that enables programmatic assignment of Validators.
For your example you can do:
It is important to keep in mind that by using this method you will overwrite your existing validators so you will need to include all the validators you need/want for the control that you are resetting.