How to update all the values of form controls inside a form group, when one of them changes?

457 Views Asked by At

I have a simple Angular form group, created with form builder that looks like this:

  filterForm = this.fb.group({
    conditions: false,
    clinicalReadings: false,
    healthRisk: this.fb.group({}),
  })

healthRisk is a nested form group of checkboxes. One of the checkboxes is 'All'. Whenever all is checked/set to true, I want all other checkboxes set to true and same for false.

I tried to subscribe to value changes of 'All' checkbox and then tried setting the value of other checkboxes inside ngOnInit():

 ngOnInit(): void {
    //this function sets the form controls for healthrisk:
    this.setOptionControls('healthRisk', true);

    const formControls = this.filterForm.controls.healthRisk.controls;
    formControls['All'].valueChanges.subscribe((val: boolean) => {
     //I tried couple changes here, that didn't work
    });
  }

I tried to use setValue, for setting new value for the form group, also tried looping and updating controls one by one, but I get 'maximum call stack size exceeded' error. Seems like I can't use setValue inside subscription, even though I have no idea why. What would be the best solution for this problem?

1

There are 1 best solutions below

0
Evgeny Gurevich On

You should not subscribe to changes of child form group. Only to 'all' control.

ngOnInit() {
    const parentForm: FormGroup = this.filterForm;
    const childForm: FormGroup = parentForm.controls.healthRisk as FormGroup;

    childForm.controls.all.valueChanges.subscribe((value) =>
      Object.keys(childForm.controls)
        .filter((key) => key !== 'all')
        .forEach((key) => (childForm.get(key) as FormControl).setValue(value))
    );
  }