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

Angular Material带搜索的多选mat-select丢失已选值问题求助

问题解决:Angular Material mat-select多选搜索后选中值丢失

问题核心原因

你遇到的问题本质是:用*ngIf过滤mat-option时,不符合搜索条件的选项会被直接从DOM中移除。而Angular Material的mat-select多选组件依赖DOM中存在的mat-option来维护选中状态——当选项被移除后,组件会默认这些选项不再有效,从而自动取消它们的选中状态。

解决方案

1. 用[hidden]替代*ngIf保留DOM元素

不要用*ngIf删除不符合条件的选项,改用[hidden]隐藏它们,让所有mat-option始终留在DOM中,这样组件就能正常维护选中状态。

2. 修正value的绑定方式

原代码中用插值语法value="{{json.stringify(group.name)}}"存在潜在问题,改用Angular属性绑定[value]="group.name"更安全可靠。

修改后的完整代码

<mat-form-field appearance="fill">
  <mat-label>Select Target Groups</mat-label>
  <mat-select formControlName="targetGroups" multiple [id]="'targetGroups'+i">
    <input 
      matInput 
      placeholder="Search for target groups" 
      type="text" 
      style="height: 35px;"
      (keyup)="searchText($event, 'groupSearch')" 
      (click)="$event.stopPropagation()"
    >
    <section>
      <ng-container *ngFor="let group of targetGroups">
        <mat-option
          [hidden]="groupSearch && !group.name?.toLowerCase().includes(groupSearch.toLowerCase())"
          [value]="group.name"
        >
          {{group.name}}
        </mat-option>
      </ng-container>
    </section>
  </mat-select>
</mat-form-field>

配套的TypeScript搜索逻辑

确保你的searchText函数正确更新搜索关键词:

searchText(event: Event, field: string): void {
  this[field] = (event.target as HTMLInputElement).value.trim().toLowerCase();
}

额外说明

  • 嵌套mat-checkbox后问题依旧,本质还是*ngIf移除DOM元素导致的,核心解决思路还是保留所有mat-option在DOM中。
  • 直接用mat-checkbox替代mat-option会破坏mat-select的内置交互逻辑,导致下拉框无法正常工作,这是组件的预期行为,不要这么做。

内容的提问来源于stack exchange,提问作者Charger-Ang

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 11:45:26