首页 > 解决方案 > 一次只选择一个复选框,并在一个特定复选框被选中或两个复选框都未选中时执行特定任务

问题描述

我有两个复选框,目标是一次只允许选择一个复选框 根据对特定复选框的选择或者如果两个复选框都未选中,则需要执行更多不同的任务。当检查一个复选框或两者都没有选中时,我在执行任务时已经实现了这一问题并面临问题。

<div *ngFor="let chk of checkboxes">
<input type="checkbox" [checked]="chk.checked" 
(click)="uncheckOther(chk)"> {{chk.value}}
</div>

TS 代码:

  checkboxes = [{ checked: false, value: 'Request' }, { checked: false, 
  value: 'Reservation' }];    

  uncheckOther(chk) {
   //uncheck all
   this.checkboxes.forEach(x => {
   if(x.checked == true)
   x.checked = false;
  })

  //check the selected
   if(chk.checked == true) {
   chk.checked = false; 
    } else {
   chk.checked = true;
   }
//Execute task if any one of the checkboxes are selected
   if(chk.value === "Request" && chk.checked == true){
    console.log("call request data")
   } else if(chk.value === "Reservation" && chk.checked == true){
    console.log("call Reservation data");
   }
//Execute task if none of them is checked
   this.checkboxes.forEach(x => {
   if(x.checked === false)
   console.log("call both combined data")
   })
   }

一次只能选择一个复选框,并且需要执行一些任务,具体取决于选定的复选框或两个复选框都未选中,这也是默认情况(或用户可能未选中)

标签: angulartypescriptcheckbox

解决方案


需要一些改动:

HTML 代码:

<div *ngFor="let chk of checkboxes">
  <input type="checkbox" [(ngModel)]="chk.checked" (ngModelChange)="uncheckOther(chk,$event)"> 
  {{chk.value}}
</div>

TS 代码:

uncheckOther(chk, event) {

  if (event) {
    //uncheck all
    this.checkboxes.forEach(x => {
      if (x.checked == true)
        x.checked = false;
    })
    //check the selected
    if (chk.checked == true) {
      chk.checked = false;
    } else {
      chk.checked = true;
    }
    if (chk.value == "Request") {
      console.log('Call Request API')
    }
    else if (chk.value == "Reservation") {
      console.log('Call Reservation API')
    }
  }
  else {
    console.log('Call Both API')
  }
}

Working Demo


推荐阅读