mercredi 10 novembre 2021

Unselect other check box when selecting one check box

In my scenario, I have 2 checkboxes. By default, both checkboxes can be false or 1 check box is true and other is false or vise versa.

User should be able to select only one checkbox and if he wants he can de-select both. Further, default values are selected using another field. if that field is empty Checkbox is false and vise versa.

NOTE

I have achieved what I want but the code looks ugly. Can anyone suggest me a clean way to achieve this.

Thanks in advance.

HTML

<input type="checkbox" id="cb1" name="cb1" (click)="unselectCheckbox()" [(ngModel)]="cb1">
<input type="checkbox" id="cb2" name="cb2" (click)="unselectCheckbox()" [(ngModel)]="cb2">

TS

  cb1 = false;
  cb2 = false;

  public unselectCheckbox() {  
    if (this.cb1) {
      this.cb2 = false;
    } else {
      this.cb1 = !this.cb1;
      this.cb2 = false;
    }
    if (this.cb2) {
      this.cb1 = false;
    } else {
      this.cb1 = !this.cb1;
    }
  }



Aucun commentaire:

Enregistrer un commentaire