Search code examples
angularangular6angular-reactive-formsangular-forms

Multiple Checkbox in Reactive Forms in Angular Table


I have a reactive forms table in my angular app and i have 3 checkbox for each row. Present, Absent and Leave. They only have the same formControlName="status". They should only click one checkbox for row. The status are as follow:

Present = 1
Absent = 2
Leave = 3

How will be i able to do this? Please check this stackblitz code: CLICK HERE

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

Solution

  • Why you are using check box you should use radio buttons. Just change the type of status form control <input type="radio"> It will work fine. I have also tested on your stackblitz code.

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