The conditional validator has probably been asked a lot. But what I could never find is when this validator is to be invoked.
Suppose I have a form with only two fields
this.form = formBuilder.group({
emailRequired: [false],
emailRecipients: ['']
});
I now want the field emailRecipients
to have a required validator ONLY when the emailRequired
field is set to true
. I came up with this
const emailRecipientsControl = fb.control('', {
validators: [
(x) =>
{
// When emailRequired is set to true, the email control is required.
if (x.parent?.get('emailRequired').value)
{
return { required: true }
};
return null;
}
]
});
this.form = this.fb.group({
emailRequired: [false],
emailRecipients: emailRecipientsControl
});
This actually somewhat works, but the problem is that my custom validator is only invoked when the emailRecipients
value has been changed, whereas I need it to be invoked when BOTH emailRecipients
or emailRequired
have been changed.
So to summarize: how do I define WHEN to invoke (custom) control validation?
Note: my real form is a lot larger then this example and I'd rather not subscribe to the entire form.