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

Mat-select多选选中值为undefined,无法获取选中值问题咨询

问题原因及解决办法

1. 响应式表单与模板驱动表单混用冲突

你同时在<mat-select>上使用了formControlName(响应式表单)和[(ngModel)](模板驱动表单),Angular中这两种表单绑定方式不能混用,会直接导致值绑定逻辑混乱,最终出现选中值为undefined的情况。

解决: 二选一即可,鉴于你已经用了formGroup,推荐保留响应式表单方案,直接移除[(ngModel)]="selectedUserType"。

2. FormControl未按多选要求初始化

多选模式的Mat-select对应的FormControl,必须初始化为空数组。如果你的filterSearchForm里的customField没有初始化,或者初始值不是数组类型,会导致选中值无法正确绑定。

检查组件类中的表单初始化代码,确保符合要求:

import { FormGroup, FormControl } from '@angular/forms';

// 组件类内部代码
filterSearchForm = new FormGroup({
  customField: new FormControl([]) // 多选场景必须初始化为空数组
});

3. 重复绑定选择事件导致逻辑混乱

你同时给<mat-select>绑定了selectionChange、给<mat-option>绑定了onSelectionChange,两个事件都会触发filterByCustomFields方法,不仅会造成重复触发,还可能导致事件对象混乱,干扰选中值的获取。

解决: 只保留<mat-select>的selectionChange事件即可,多选场景下该事件的$event.value就是选中值的数组:

<mat-select [formControlName]="'customField'" [multiple]="true" placeholder="בחר" (selectionChange)="filterByCustomFields($event)">
  <mat-option *ngFor="let custom of filteredRows" [value]="custom.value">
    {{custom.fieldHebKey}}
  </mat-option>
</mat-select>

组件类中处理事件的代码可以简化为:

filterByCustomFields(event: any) {
  const selectedValues = event.value; // 此处即为选中值组成的数组
  console.log(selectedValues);
}

4. 检查filteredRows的数据有效性

确保filteredRows数组中每个custom对象的value属性存在且不为undefined——如果custom.value本身就是无效值,选中后自然无法获取到有效内容。

可以在模板中临时添加调试内容验证:

<mat-option *ngFor="let custom of filteredRows" [value]="custom.value">
  {{custom.fieldHebKey}} - {{custom.value}} <!-- 查看value是否存在有效值 -->
</mat-option>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 16:50:21