You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现单选按钮同一时间仅选中一个?Angular现有代码适配咨询

问题根因
  • 同组单选按钮需要设置完全一致的name属性才能实现互斥选中,你当前代码中四个单选按钮的name属性各不相同,相当于被识别为4组独立的单选框,因此支持同时选中。
  • 同时使用[(ngModel)]和[(checked)]两个双向绑定会产生逻辑冲突,且同组单选框只需要绑定同一个公共变量即可,不需要为每个单选框单独绑定独立的ngModel和checked变量。
  • 每个单选框单独绑定change事件也属于冗余逻辑,可统一处理。
调整方案

第一步:修改组件TS代码

新增公共变量存储当前选中的单选值,合并原来的多个toggle方法为统一处理逻辑:

// 存储当前选中的阈值选项,可设置默认值比如0
selectedThreshold: number = 0;

// 统一处理阈值切换逻辑
onThresholdChange(selectedVal: number) {
  // 你原来的toggle逻辑可根据selectedVal判断执行,比如:
  switch(selectedVal) {
    case 0: 
      // 对应原来toggleShowAreaOfCoverageWithThreshold3的逻辑
      break;
    case 1:
      // 对应原来toggleShowAreaOfCoverageWithThreshold10的逻辑
      break;
    case 2:
      // 对应原来toggleShowAreaOfCoverageWithThreshold15的逻辑
      break;
    case 3:
      // 对应原来toggleShowAreaOfCoverageWithThreshold20的逻辑
      break;
  }
}

第二步:修改模板HTML代码

统一所有单选框的name属性,绑定同一个ngModel变量,删除冗余的checked绑定和独立change事件:

<div class="modal-body">
  <input [value]="0" [(ngModel)]="selectedThreshold" name="areaCoverageThreshold" type="radio" (change)="onThresholdChange(selectedThreshold)" />
  <label id="threshold-value-3">
    {{ "SITE.AREA_OF_COVERAGE_FOR_THRESHOLD_3" | translate }}
    <button class="btn btn-sm btn-icon" (click)="showInformation('SERVICE_DIST_4_AGRI')">
      <clr-icon shape="help-info" class="is-solid"></clr-icon>
    </button>
  </label>
  <input [value]="1" [(ngModel)]="selectedThreshold" name="areaCoverageThreshold" type="radio" (change)="onThresholdChange(selectedThreshold)" />
  <label id="threshold-value-10">
    {{ "SITE.AREA_OF_COVERAGE_FOR_THRESHOLD_10" | translate }}
    <button class="btn btn-sm btn-icon" (click)="showInformation('SERVICE_DIST_4_AGRI')">
      <clr-icon shape="help-info" class="is-solid"></clr-icon>
    </button>
  </label>
  <input [value]="2" [(ngModel)]="selectedThreshold" name="areaCoverageThreshold" type="radio" (change)="onThresholdChange(selectedThreshold)" />
  <label id="threshold-value-15">
    {{ "SITE.AREA_OF_COVERAGE_FOR_THRESHOLD_15" | translate }}
    <button class="btn btn-sm btn-icon" (click)="showInformation('SERVICE_DIST_4_AGRI')">
      <clr-icon shape="help-info" class="is-solid"></clr-icon>
    </button>
  </label>
  <input [value]="3" [(ngModel)]="selectedThreshold" name="areaCoverageThreshold" type="radio" (change)="onThresholdChange(selectedThreshold)" />
  <label id="threshold-value-20">
    {{ "SITE.AREA_OF_COVERAGE_FOR_THRESHOLD_20" | translate }}
    <button class="btn btn-sm btn-icon" (click)="showInformation('SERVICE_DIST_4_AGRI')">
      <clr-icon shape="help-info" class="is-solid"></clr-icon>
    </button>
  </label>
</div>

修改后同组单选框会自动实现互斥选中效果,无需额外手动控制选中状态。

内容的提问来源于stack exchange,提问作者Amrmsmb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 18:45:02