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

如何实现点击新mat-checkbox时取消之前选中的复选框

实现Mat-Checkbox单选效果(点击新选项取消之前选中项)

问题分析

你当前的代码未将mat-checkbox与表单控件正确绑定,也未实现单选逻辑,导致点击新复选框时无法取消之前的选中项。以下是具体解决方案:

修改后的HTML代码

<form [formGroup]="deleteform" (submit)="submit()">
  <ul>
    <li *ngFor="let test of getvalue?.food">
      <mat-checkbox 
        [disableRipple]="true" 
        [value]="test.id"
        [checked]="deleteform.get('selectedFoodId')?.value === test.id"
        (change)="onFoodCheckboxChange(test.id)"
        aria-label="Value">
        {{test?.category[currentval]}}
      </mat-checkbox>
    </li>
    <mat-checkbox 
      [checked]="deleteform.get('selectedFoodId')?.value === null"
      (change)="onNoneOfAboveChange($event)">
      None of Above
    </mat-checkbox>
  </ul>
  <button type="submit">submit</button>
</form>

修改后的TS代码

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({
  // 你的组件元数据
})
export class YourComponent implements OnInit {
  deleteform: FormGroup;
  getvalue: any; // 你的数据源
  currentval: any; // 你的当前值变量

  constructor(private fb: FormBuilder) {}

  ngOnInit(): void {
    this.deleteform = this.fb.group({
      selectedFoodId: [null, Validators.required] // 单个控件存储选中项,null对应"None of Above"
    });
  }

  onFoodCheckboxChange(selectedId: number): void {
    // 选中食物复选框时,更新表单值,自动取消其他复选框选中状态
    this.deleteform.patchValue({ selectedFoodId: selectedId });
  }

  onNoneOfAboveChange(event: any): void {
    if (event.checked) {
      // 选中"None of Above"时,重置选中的食物ID为null
      this.deleteform.patchValue({ selectedFoodId: null });
    } else {
      // 取消选中时,恢复必填校验(可根据需求调整)
      this.deleteform.get('selectedFoodId')?.setValidators(Validators.required);
      this.deleteform.get('selectedFoodId')?.updateValueAndValidity();
    }
  }

  submit(): void {
    if (this.deleteform.valid) {
      console.log('选中的值:', this.deleteform.value.selectedFoodId);
      // 处理提交逻辑
    }
  }
}

关键说明

  • 用单个表单控件selectedFoodId统一管理选中状态:选中具体食物时存储对应ID,选中"None of Above"时存储null。
  • 通过[checked]属性同步复选框与表单控件的状态,确保两者一致。
  • 点击食物复选框时,通过onFoodCheckboxChange更新表单值,自动取消其他复选框的选中状态。
  • 点击"None of Above"时,通过onNoneOfAboveChange重置选中ID为null,同时取消所有食物复选框的选中状态。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 07:10:45