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

如何通过代码取消Angular Material多选框的选中状态?

解决Angular Material多选下拉框标签移除后状态不同步问题

你的核心问题是同时混用了响应式表单的FormControl和模板驱动的ngModel,且修改选中项时未同步更新FormControl的值,导致mat-select的内部选中状态和你维护的selectedElts不一致。

mat-select的多选状态完全由绑定的FormControl(即你的toppings变量)控制,而非ngModel或自定义的selectedElts。你之前修改selectedElts后没有更新FormControl的值,所以下拉框的内部选中状态没有变化;同时点击其他选项时,FormControl的新值会覆盖selectedElts,导致之前的修改丢失。

修复步骤:

  1. 移除[(ngModel)]绑定:Angular不建议同时混用响应式表单和模板驱动表单,会导致状态冲突。
  2. 用FormControl统一管理选中状态:直接从toppings.value获取选中项,无需单独维护selectedElts。
  3. 修改remove方法,同步更新FormControl的值:通过setValue方法更新toppings的value,让mat-select的内部状态同步变化。

修改后的代码:

HTML:

<mat-form-field>
  <mat-label>Toppings</mat-label>
  <mat-select [formControl]="toppings" multiple>
    @for (topping of toppingList; track topping) {
    <mat-option [value]="topping">{{topping}}</mat-option>
    }
  </mat-select>
</mat-form-field>

<div>
  @for (topping of toppings.value || []; track topping) {
  <button (click)="remove(topping)">{{topping}}</button>
  }
</div>

TS:

import { Component } from '@angular/core';
import { FormControl, FormsModule, ReactiveFormsModule } from '@angular/forms';
import { MatSelectModule } from '@angular/material/select';
import { MatFormFieldModule } from '@angular/material/form-field';

/** @title Select with multiple selection */
@Component({
  selector: 'select-multiple-example',
  templateUrl: 'select-multiple-example.html',
  standalone: true,
  imports: [
    MatFormFieldModule,
    MatSelectModule,
    FormsModule,
    ReactiveFormsModule,
  ],
})
export class SelectMultipleExample {
  // 初始化FormControl为空数组,匹配多选的数组类型
  toppings = new FormControl<string[]>([]);
  toppingList: string[] = [
    'Extra cheese',
    'Mushroom',
    'Onion',
    'Pepperoni',
    'Sausage',
    'Tomato',
  ];
  output: string;

  public remove(topping: string) {
    // 过滤掉要移除的项,生成新数组
    const newSelected = (this.toppings.value || []).filter(item => item !== topping);
    // 更新FormControl的值,同步mat-select的内部状态
    this.toppings.setValue(newSelected);
  }
}

关键说明:

  • 初始化toppings时指定类型为string[],并设置初始值为空数组,避免空字符串导致的类型不匹配问题。
  • 移除项时通过filter生成新数组(不要用splice修改原数组,因为FormControl依赖不可变值来触发变化检测),再用setValue更新,确保mat-select的内部选中状态同步更新。
  • 直接使用toppings.value渲染标签,无需额外维护selectedElts,减少状态不一致的风险。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 10:25:31