angular - 一次只选择一个复选框并在选中的特定复选框或未选中的两个复选框上执行特定任务

标签 angular typescript checkbox

我有两个复选框,目标是一次只允许选中一个复选框 根据特定复选框的选择或两个复选框均未选中的情况,需要执行更多不同的任务。 我已经实现了这一点,并且在选中一个复选框或两个都未选中时执行任务时遇到问题

<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")
   })
   }

一次只能选中一个复选框,并且需要根据选中的复选框或两个复选框都未选中来执行某些任务,这也是默认情况(或者可能被用户取消选中)

最佳答案

需要做一些改动:

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

关于angular - 一次只选择一个复选框并在选中的特定复选框或未选中的两个复选框上执行特定任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55633367/

相关文章:

javascript - 如何获取分页上选中的复选框的数量 Jquery dataTables

jquery - 使用 jQuery 显示/隐藏动态添加的 div

angular - 如何在 Angular 7中动态显示表格的行数据

angular - 如何检测 Angular 2 组件是否具有属性

typescript - 如何使用带有 JSX/TSX 的 TypeScript 转换

typescript 类型排除?

javascript - 如何检查按键上的复选框?

angular - 分页在 api 系统中是如何工作的(前端是 Angular 2,后端是 laravel 5.4)?

javascript - 根据条件将两个 Angular Material 选择之一设置为所需

typescript - 强制 typescript 将方法放在实例而不是原型(prototype)上