Reputation:
I'm using Angular 8 and I would like the form fields of my form group only be required when any other field of the same form group is filled, is there any simple way to do that or do I need to create a custom function to verify if the other form fields were filled?
const CredentialsXYZ: CredentialsXYZ= {
token: [res.token, [Validators.required]],
user: [res.user, [Validators.required]],
password: [res.password, [Validators.required]]
};
Upvotes: 2
Views: 3164
Reputation: 91
Since Angular 13, you can add validators dynamically, like this:
this.formName.controls.controlName.setValidators(Validator.required);
or, if the control had any validator before -
this.formName.controls.controlName.addValidators(Validator.required);
You can do it by subscribing to valueChanges
of the control you depend on. For example:
const userField = form.controls.user
const passwordField = form.controls.user
userField.valueChanges.subscribe(user => {
if (user) {
passwordField.setValidators(Validators.required)
} else {
passwordField.clearValidators()
}
// Remember to call this for the new validation to take place immediately
passwordField.updateValueAndValidity()
})
Upvotes: 5