如何使用Angular绑定表单中的复选框列表? [英] How can I bind a list of checkboxes in a form using Angular?

查看:65
本文介绍了如何使用Angular绑定表单中的复选框列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表单,其中包含供用户检查的复选框列表,然后在用户提交表单时,它应将复选框列表作为对象数组提交.相反,我什么也没得到.

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. Instead, I'm getting nothing.

我在控制台中得到什么: {fruits:Array [0]}

What I'm getting in the console: {fruits: Array[0]}

我所期望的: {fruits:Array [1]}//数组的数量取决于选中的复选框

下面是 stackblitz

推荐答案

这是一个类似Netanel Basal的方法(仅更改Submit功能).如果我们以形式"来思考谁的价值可以像例如

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;
    }
  }

结果"为例如

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

是的,我们确实是复杂的提交",但是另一方面,我们的形式变得像

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

<form *ngIf="myForm" [formGroup]="myForm" (submit)="submit(myForm)">
  <div formArrayName="myChoices">
  <div *ngFor="let choice of myForm.get('myChoices').controls; let i=index" class="col-md-2">
    <label>
      <input type="checkbox" [formControlName]="i">
      {{checks[i].description}}
    </label>
  </div>
  </div>
  <button type="submit">submit</button>
</form>

不具有外部功能,不能再打一按即可移除等好吧,唯一的办法就是创建类似

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)))
    });
  }

请参见 stackblitz

这篇关于如何使用Angular绑定表单中的复选框列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆