0
votes

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]
    }))
  }
2
If you don't need to check more than one checkbox at the same time, may be it would be better using of radio group instead of checkbox?Ken Bekov
@KenBekov. Yeah you're right. you can fork my stackblitz anyway. ThanksJoseph

2 Answers

0
votes

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

It can be done with checkboxes as well but based on your requirement it will always be feasible and more efficient to use the radio buttons since it by default provides you the functionality of choosing only one option whereas in case of checkboxes you will have to write down more code explicitly to provide it the same functionality which in turn increases your codebase and does no good.

Go ahead with what @Debabrata Paul Chowdhury has provided.