0

I have roughly 150 checkboxes within a form group the checkboxes are made up of 15 sections (form arrays)

That, to begin with, are hidden, when a radio is clicked, a validator is attached to the form group and a list of categories are shown, when the list is clicked on, the corresponding checkboxes are shown

The validator function uses a service that tracks which checkboxes are checked. If there are any then ok, if none the throw an error

The issue is when I click the radio button to remove the validator, the validator function is called thousands of times, before removal

Which slows down the app, also if I click remove and add the validator button multiple times it gets worse, taking longer to show the list.

After this, if I click a checkbox, the app can become unresponsive, because of how long it's taking to iterate through the function/s

Function to set and remove validation:

 onSelected(): void {
    const myFormGroup: AbstractControl = this.form.controls.theFormGroup;
        if (this.form.get('myButton').value === 'Yes') {
            myFormGroup.validator = ModValidation.requireCheckboxesToBeChecked(this.stateService);
            } else {
        //Exucutes thousands of validation calls before it gets here
        myFormGroup.setErrors(null);
        myFormGroup.setValidators(null);
        myFormGroup.reset();
        }
    myFormGroup.updateValueAndValidity();

}

I've tried getting the value of

Validator:

static requireCheckboxesToBeChecked(stateService: StateService): ValidatorFn {
   return (formGroup: FormGroup): { [key: string]: boolean } | null => {
      const checkedCount = stateService.currentCheckedCount();
      if (checkedCount === 0) {
          return  {
            'isNotChecked' : true
          };
        }
      return null;
    };
  }

Function to return checked checkboxes:

  currentCheckedCount(): number {
    let sumOfAllChecked = 0;
    Object.keys(this.store).forEach((category: string) => {
      this.store[category].forEach((item) => {
       if (item.checked)  {
         sumOfAllChecked += 1;
        }
      });
    });
    return sumOfAllChecked;
  }
RasMason
  • 1,968
  • 4
  • 32
  • 54
  • 1
    try disabled the controls you don't want validate instead of change the validator. (use a directive to enabled/disabled) https://stackoverflow.com/questions/54517613/dynamic-validations-in-angular-7-enable-setvalidators-depending-on-flags-tr – Eliseo Feb 27 '19 at 07:56
  • Thanks for the tip, will try and let you know – RasMason Feb 27 '19 at 08:00

0 Answers0