You need to enable JavaScript to run this app. Angular带搜索筛选的mat-select多选下拉切换筛选后已选值清空问题
优惠活动
大模型
产品
解决方案
定价
更多

Angular带搜索筛选的mat-select多选下拉切换筛选后已选值清空问题

问题根因

你遇到的跨筛选条件选择时已选值被清空的问题,本质是两个实现细节踩了Material组件的设计逻辑:

  1. 原代码给mat-form-field绑定的*ngIf判断条件直接关联了筛选后的列表长度,一旦筛选结果变化、列表长度变动,整个表单控件会被销毁重建,直接触发绑定值重置。
  2. mat-select多选模式下,只有渲染到DOM中的mat-option,才能被组件识别为合法的选中值。当你修改筛选关键词后,之前选中的员工如果不在当前筛选结果里,对应的mat-option会被直接移除出DOM,mat-select找不到对应的匹配项,就会自动把这些值从checkedEmployees数组中清除。
最低成本可行解决方案

核心思路是:永远把已选中的员工保留在option渲染列表里,不会因为筛选条件被过滤掉,让mat-select始终能识别到已选值,就不会出现清空的问题。
具体修改步骤:

  • 移除原代码里和筛选结果绑定的*ngIf,只判断原始全量员工列表是否加载完成,避免控件被不必要的销毁重建。
  • 调整筛选逻辑,最终用来渲染mat-option的列表,由「已选中但不在当前筛选结果里的员工」+「当前关键词筛选匹配的员工」组成,同时通过员工唯一ID做去重,避免重复渲染。

修改后的代码如下:

Typescript 部分

// 全量员工列表,保持不变
employeeOptions: Employee[] = [];
// 筛选后供渲染的option列表
filteredEmployeeOptions: Employee[] = [];
// 已选员工数组,保持不变
checkedEmployees: Employee[] = [];

filterItem(event: string){
  // 1. 先计算当前关键词匹配的员工列表
  const matchedResult = !event 
    ? this.employeeOptions 
    : this.employeeOptions.filter(employee => 
        employee.firstName.toLowerCase().startsWith(event.toLowerCase()) 
        || employee.lastName.toLowerCase().startsWith(event.toLowerCase())
      );
  
  // 2. 找出已经被选中、但不在当前匹配结果里的员工,确保对应的option不会被移除
  const selectedNotInMatched = this.checkedEmployees.filter(
    selectedEmp => !matchedResult.some(matchedEmp => matchedEmp.id === selectedEmp.id)
  );

  // 3. 合并为最终渲染列表,避免重复项
  this.filteredEmployeeOptions = [...selectedNotInMatched, ...matchedResult];
}

注意:列表去重时一定要用员工的唯一标识(如员工ID)判断,不要直接对比对象引用,否则会因为对象内存地址不一致出现重复渲染、选中匹配失败的问题。

HTML 部分

<!-- 移除原逻辑中绑定筛选结果的*ngIf,只判断全量列表加载状态 -->
<mat-form-field appearance="fill" class="p-1rem" *ngIf="employeeOptions?.length > 0">
  <input 
    matInput 
    type="text" 
    name="search" 
    placeholder="Search" 
    (ngModelChange)="filterItem($event)" 
    [(ngModel)]="filterText">
  <mat-label>{{'SHARED.EMPLOYEE_NAME' | translate}}</mat-label>
  <mat-select 
    [(ngModel)]="checkedEmployees" 
    name="employeeName" 
    required 
    multiple>
    <!-- 循环合并后的渲染列表 -->
    <mat-option 
      [value]="employee" 
      *ngFor="let employee of filteredEmployeeOptions">         
      {{employee.lastName}} {{employee.firstName}}
    </mat-option>    
  </mat-select>
</mat-form-field>

这样修改后,哪怕你修改筛选关键词,之前选中的员工对应的option也不会从DOM中移除,mat-select始终能正确识别已选值,不会清空checkedEmployees数组,就可以实现跨不同筛选条件多选员工的需求。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.10 18:36:10