在Angular中如何实现复选框单选 限制用户仅可勾选一个复选框
Angular 复选框单选限制实现方案
修改思路
- 每次选中新选项时清空其余所有复选框的选中状态,实现单选约束
- 取消选中时清空所有存储选中值的变量,无选中时不返回任何内容
- 将当前操作的产品对象直接传入事件处理函数,简化取值逻辑
完整修改代码
HTML 部分
<div class="form-check" *ngFor="let product of DisplayProductList"> <label class="form-check-label text-break"> <input class="form-check-input" type="checkbox" [value]="true" [(ngModel)]="product.isChecked" (change)="changeSelection($event, product)" /> {{ product.template_name }} <span class="form-check-sign"> <span class="check"></span> </span> </label> </div>
逻辑代码部分
changeSelection(event: any, currentProduct: any) { // 先清空所有选中相关变量,避免旧值残留 this.checkedIDs = []; this.selectedItemsList = []; this.variable1 = ''; this.variable2 = ''; if (event.target.checked) { // 单选核心逻辑:将除当前选中项外的所有选项选中状态设为false this.DisplayProductList.forEach(product => { if (product.id !== currentProduct.id) { product.isChecked = false; } }); // 处理当前选中项的取值逻辑 const splitstring = currentProduct.template_parameter; const sepratedArray = splitstring.split(','); this.variable1 = sepratedArray[0]; this.variable2 = sepratedArray[1]; this.checkedIDs.push(currentProduct.id); this.selectedItemsList.push(currentProduct); // 若原业务逻辑需要传选中产品id,可将入参改为currentProduct.id this.sendclusteridApi(currentProduct.id); } // 取消选中时已清空所有变量,无任何内容返回 }
逻辑说明
- 无需修改原业务的取值逻辑,仅新增单选控制的遍历逻辑即可实现需求
- 所有选中状态和相关变量完全同步,不会出现状态不一致的问题
- 无选中状态下所有存储选中值的变量均为空,不会返回无效内容
内容的提问来源于stack exchange,提问作者Mercy
相关产品推荐
相关产品推荐

