How can I bind a list of checkboxes in a form using Angular?

前端 未结 2 941
执念已碎
执念已碎 2021-01-26 18:10

I have a form that contains a list of checkboxes for the user to check and then when the user submit the form, it should submit the list of checkboxes as an array of objects. In

2条回答
  •  长情又很酷
    2021-01-26 18:39

    It's an aproach like Netanel Basal (only change the submit function). The things goes more fluid if we think in a Form who value can be like e.g.

    {
      "otherControls": "",
      "myChoices": [
        false,
        true,
        false
      ]
    }
    

    Well, we don't want this ugly data, but we can, in submit write some like

    submit(myForm) {
        if (myForm.valid) {
          const value = { ...myForm.value };
          value.myChoices = this.checks
            .filter((x, index) => myForm.value.myChoices[index])
            .map(x => x.value);
          this.result = value;
        }
      }
    

    And "result" will be,e.g.

    {
      "otherControls": "",
      "myChoices": [
        "value2"
      ]
    }
    

    Well, its true that we are complex the "submit", but in another hand, our form becomes like

    NOT externals function, not fight agains remove at push,etc Well, the only is create the form like

    initModelForm(): FormGroup {
        return this._fb.group({
          otherControls: [""],
          myChoices: new FormArray(this.checks.map(x => new FormControl(false)))
        });
      }
    

    See stackblitz

提交回复
热议问题