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
相关产品推荐
相关产品推荐

