How to validate that at least one checkbox should be selected?

后端 未结 6 1847
遇见更好的自我
遇见更好的自我 2020-12-04 22:20

I want to do validation for checkboxes here without form tag. At least one checkbox should be selected.



        
6条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-04 22:48

    consider creating a FormGroup which contains your check-box group and bind the group's checked value to a hidden formcontrol with a required validator.

    Assume that you have three check boxes

    items = [
      {key: 'item1', text: 'value1'},      // checkbox1 (label: value1)
      {key: 'item2', text: 'value2'},      // checkbox2 (label: value2)
      {key: 'item3', text: 'value3'},      // checkbox3 (label: value3)
    ];
    

    Step1: define FormArray for your check boxes

    let checkboxGroup = new FormArray(this.items.map(item => new FormGroup({
      id: new FormControl(item.key),      // id of checkbox(only use its value and won't show in html)
      text: new FormControl(item.text),   // text of checkbox(show its value as checkbox's label)
      checkbox: new FormControl(false)    // checkbox itself
    })));
    

    *easy to show via ngFor

    Step2: create a hidden required formControl to keep status of checkbox group

    let hiddenControl = new FormControl(this.mapItems(checkboxGroup.value), Validators.required);
    // update checkbox group's value to hidden formcontrol
    checkboxGroup.valueChanges.subscribe((v) => {
      hiddenControl.setValue(this.mapItems(v));
    });
    

    we only care about hidden control's required validate status and won't show this hidden control in html.

    Step3: create final form group contains below checkbox group and hidden formControl

    this.form = new FormGroup({
      items: checkboxGroup,
      selectedItems: hiddenControl
    });
    

    Html Template:

    checkbox group is required!

    {{form.controls.selectedItems.value | json}}

    refer this demo.

提交回复
热议问题