【问题标题】:Unselect other check box when selecting one check box选中一个复选框时取消选中另一个复选框
【发布时间】:2021-12-23 08:44:34
【问题描述】:

在我的场景中,我有 2 个复选框。默认情况下,两个复选框都可以为 false 或 1 个复选框为 true,其他为 false,反之亦然。

用户应该能够只选择一个复选框,如果他愿意,他可以取消选择两个。此外,使用另一个字段选择默认值。如果该字段为空复选框为 false,反之亦然。

注意

我已经实现了我想要的,但是代码看起来很难看。谁能建议我一个干净的方法来实现这一点。

提前致谢。

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;
    }
  }

【问题讨论】:

    标签: html angular typescript checkbox


    【解决方案1】:

    HTML

     <input
          type="checkbox"
          id="cb1"
          name="cb1"
          (change)="unselectCheckbox($event, 'checkbox1')"
          [(ngModel)]="cb1"
        />
        <input
          type="checkbox"
          id="cb2"
          name="cb2"
          (change)="unselectCheckbox($event, 'checkbox2')"
          [(ngModel)]="cb2"
        />
    

    TS

    public unselectCheckbox(event, opt) {
        console.log(event.target.checked);
        if (opt == 'checkbox1') {
          this.cb1 = event.target.checked;
          this.cb2 = false;
        }
        if (opt == 'checkbox2') {
          this.cb2 = event.target.checked;
          this.cb1 = false;
        }
      }
    

    在 HTML 中,(change) 事件值向 TS 传递了两个参数。

    我觉得这看起来很干净。

    【讨论】:

      猜你喜欢
      • 2018-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-16
      • 2020-06-18
      • 2013-08-15
      相关资源
      最近更新 更多