【问题标题】:How can I bind a list of checkboxes in a form using Angular?如何使用 Angular 在表单中绑定复选框列表?
【发布时间】:2020-02-09 04:54:00
【问题描述】:

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

我在控制台中得到的信息: {fruits: Array[0]}

我的预期: {fruits: Array[1]} // The numbers of array depends on the checkbox checked

这里有一个stackblitz 的例子

【问题讨论】:

标签: javascript angular typescript


【解决方案1】:

除了表单初始化之外,你已经完成了所有工作

myForm: FormGroup = this.initModelForm();

完整代码为: 我正在控制台记录 formArray 值

import { Component } from '@angular/core';
import { FormGroup, FormArray, FormControl, FormBuilder } from '@angular/forms';

export interface Fruit {
  uid: string;
  name: string;
}

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent   {
public checks = [
  {description: 'descr1', value: 'value1'},
  {description: "descr2", value: 'value2'},
  {description: "descr3", value: 'value3'}
];

myForm: FormGroup = this.initModelForm();

constructor(
  public _fb: FormBuilder
) { }

initModelForm(): FormGroup{
  return this._fb.group({
    otherControls: [''],
    myChoices: new FormArray([])
  })
}

onCheckChange(event) {
  console.log(event);
  const formArray: FormArray = this.myForm.get('myChoices') as FormArray;

  /* Selected */
  if(event.target.checked){
    // Add a new control in the arrayForm
    formArray.push(new FormControl(event.target.value));
  }
  /* unselected */
  else{
    // find the unselected element
    let i: number = 0;

    formArray.controls.forEach((ctrl: FormControl) => {
      if(ctrl.value == event.target.value) {
        // Remove the unselected element from the arrayForm
        formArray.removeAt(i);
        return;
      }

      i++;
    });
  }
  console.log(formArray.value);
}
}

【讨论】:

    【解决方案2】:

    这是一种类似于 Netanel Basal 的方法(仅更改提交功能)。如果我们以一个价值可以像这样的形式思考,事情就会变得更加流畅,例如

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

    好吧,我们不想要这些丑陋的数据,但是我们可以,在提交时写一些类似的东西

    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"
      ]
    }
    

    好吧,我们确实是复杂的“提交”,但另一方面,我们的表单变得像

    <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 功能,在 push 时不反击删除等 好吧,唯一的就是创建这样的表单

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

    stackblitz

    【讨论】:

      猜你喜欢
      • 2019-02-07
      • 1970-01-01
      • 2012-11-23
      • 1970-01-01
      • 1970-01-01
      • 2013-01-08
      • 2014-07-22
      • 2020-02-11
      • 2021-06-10
      相关资源
      最近更新 更多