如果我有两个复选框,我该怎么做才能让一个被选中另一个不被选中?

If I have two check boxes how do I make it so that if one is checked the other is unchecked?

我正在开发一个应用程序,其中一个页面要求用户选择 credit/card 或现金付款。我想使两个复选框不能同时被选中(如果一个被选中,另一个未被选中)。

我已经尝试使用 ionChange 创建一个事件,这样如果其中一个被选中,其他复选框的布尔值就会变为 false。

HTML

 <ion-item>
    <ion-label>Credit/Debit Card (N/A)</ion-label>   
    <ion-checkbox item-start [(ngModel)]='CC' (ionChange)="checked()"></ion-checkbox>
  </ion-item>
  <br/><br/>

  <ion-item>
    <ion-label>Cash</ion-label>
    <ion-checkbox item-start [(ngModel)]='Cash' (ionChange)="checked()"></ion-checkbox>
  </ion-item>

打字稿

 Cash = false;    
  CC = false;      

  checked(){
    if(this.Cash == true){
      this.CC = false;
    }

    if(this.CC == true){
      this.Cash = false
    }
  }

我预计这会起作用,但仍然可以选中这两个框。

这个问题有不同方法的非常好的答案here

解决这个问题的最佳方法是使用 Radio-button 而不是 Checkbox 。但是如果你想 通过复选框比代码如下:-

HTML

 <input type="checkbox" name="1" [(ngModel)]="check1"
 (change)="onchange($event)"/>
 {{check1}}


 <input type="checkbox" name="2" [(ngModel)]="check2"
  (change)="onchange1($event)"/>
 {{check2}}

TypeScript

export class AppComponent {

  check1: boolean;
  check2: boolean;

  onchange(event: any) {
    if (this.check1 == !event.target.checked) {
      this.check2 = true;
    }
    else {
      this.check2 = false;
    }
  }

  onchange1(event: any) {
    if (this.check2 == !event.target.checked) {
      this.check1 = true;
    }
    else {
      this.check1 = false;
    }
  }
}

希望它对你有用。