【问题标题】:Multiple Checkbox in Reactive Forms in Angular TableAngular 表中反应式表单中的多个复选框
【发布时间】:2019-07-04 03:00:15
【问题描述】:

我的 Angular 应用程序中有一个反应式表格,每行有 3 个复选框。 在场、缺席和离开。它们只有相同的 formControlName="status"。他们应该只点击一个复选框。状态如下:

现在 = 1
缺席 = 2
离开 = 3

我将如何做到这一点? 请检查此 stackblitz 代码:CLICK HERE

initGroup() {
    let rows = this.form.get('rows') as FormArray;
    rows.push(this.fb.group({
      name: [null, Validators.required],
      status: [null, Validators.required]
    }))
  }

【问题讨论】:

  • 如果您不需要同时选中多个复选框,使用单选组而不是复选框会更好吗?
  • @KenBekov。是啊,你说得对。无论如何,你可以分叉我的 stackblitz。谢谢

标签: angular angular6 angular-reactive-forms angular-forms


【解决方案1】:

为什么要使用复选框,您应该使用单选按钮。只需更改状态表单控件的类型<input type="radio"> 即可。我还测试了你的 stackblitz 代码。

<tbody>
      <tr *ngFor="let row of form.controls.rows.controls; let i = index" [formGroupName]="i">
        <td>          
          <div class="form-group row">
            <input type="text" formControlName="name">
          </div>
        </td>
        <td>
          <input type="radio" class="custom-control-input" id="customcheckbox{{i}}" formControlName="status" value=1><label class="custom-control-label" for="customcheckbox{{i}}"></label>
        </td>
        <td>
          <input type="radio" class="custom-control-input" id="customcheckbox{{i}}" formControlName="status" value=2><label class="custom-control-label" for="customcheckbox{{i}}"></label>
        </td>
        <td>
          <input type="radio" class="custom-control-input" id="customcheckbox{{i}}" formControlName="status" value=3><label class="custom-control-label" for="customcheckbox{{i}}"></label>
        </td>
        <td>
          <button type="button" class="btn btn-square btn-danger btn-sm waves-effect waves-light"  (click)="onDeleteRow(i)"> <i class="icofont icofont-ui-delete"></i> Remove</button>
        </td>
      </tr>
    </tbody>

【讨论】:

    【解决方案2】:

    也可以使用复选框来完成,但根据您的要求,使用单选按钮总是可行且更有效,因为它默认为您提供仅选择一个选项的功能,而在复选框的情况下,您将拥有明确地写下更多代码以提供相同的功能,这反过来又增加了您的代码库并且没有好处。

    继续使用@Debabrata Paul Chowdhury 提供的内容。

    【讨论】:

      猜你喜欢
      • 2022-01-11
      • 2018-01-23
      • 2019-07-10
      • 2019-05-29
      • 1970-01-01
      • 1970-01-01
      • 2021-01-12
      • 2022-01-11
      • 1970-01-01
      相关资源
      最近更新 更多