Requiring a checkbox to be checked

后端 未结 11 1938
猫巷女王i
猫巷女王i 2020-12-25 09:51

I want a button to be disabled until a checkbox has been checked using a FormBuilder for Angular. I don\'t want to explicitly check the value of the checkbox and would prefe

11条回答
  •  清酒与你
    2020-12-25 10:13

    For Angular 8, I did it like the below for checking if atleast one checkbox is checked amongst three checkboxes

    form = new FormGroup({
        // ...more form controls...
        myCheckboxGroup: new FormGroup({
          myCheckbox1: new FormControl(false),
          myCheckbox2: new FormControl(false),
          myCheckbox3: new FormControl(false),
        }, requireCheckboxesToBeCheckedValidator()),
        // ...more form controls...
      });
    

    created a custom validator

    import { FormGroup, ValidatorFn } from '@angular/forms';
    
    export function requireCheckboxesToBeCheckedValidator(minRequired = 1): ValidatorFn {
      return function validate (formGroup: FormGroup) {
        let checked = 0;
    
        Object.keys(formGroup.controls).forEach(key => {
          const control = formGroup.controls[key];
    
          if (control.value === true) {
            checked ++;
          }
        });
    
        if (checked < minRequired) {
          return {
            requireCheckboxesToBeChecked: true,
          };
        }
    
        return null;
      };
    }
    

    and used it like below in html

    
       
    
       
    At least one checkbox is required to check

提交回复
热议问题