角表中反应形式的多个复选框

时间:2019-07-04 03:00:15

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

我在我的角度应用程序中有一个反应式表格表格,每行有3个复选框。 现在,缺席和离开。它们仅具有相同的formControlName =“ status”。他们应该只单击一个复选框进行行。状态如下:

现在= 1
缺席= 2
假= 3

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

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

2 个答案:

答案 0 :(得分:0)

为什么要使用复选框,应该使用单选按钮。只需更改状态表单控件<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>

答案 1 :(得分:0)

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

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