2

I have a reactive form like this

this.form = this.formBuilder.group({
  ...
  email: [],
  receiveNewsletter: [],
  ...
})

I want all fields to be optional, except if user checks receiveNewsletter, the email field should be required. How can i do that?

1 Answers1

1

You have to watch the value of the checkbox and add or remove the required validator based on the value of receiveNewsletter

this.form.controls.receiveNewsletter.valueChanges.subscribe(value => {
   if(value){
      this.form.controls.email.addValidators(Validator.required);
   } else {
      this.form.controls.email.removeValidators(Validator.required);
   }
   this.form.controls.email.updateValueAndValidity(); //remember to add this to update the form control state
})
Haris Bouchlis
  • 2,366
  • 1
  • 20
  • 35
  • 1
    I suggest another approach, a [custom validator "requiredIf"](https://stackoverflow.com/questions/65012294/remove-specific-validator-from-the-formgroup-in-angular/65013492#65013492) – Eliseo May 31 '22 at 08:56