Angular Material多选下拉选中项为undefined问题及解决方法
解决Angular Material多选下拉选中值获取问题
你在使用Angular Material多选下拉时遇到了获取选中值返回undefined的问题,下面针对你给出的两种实现方式分析问题,并提供正确的最佳实践:
第一种方式问题分析与修正
你的第一种实现使用了[(value)]绑定,但多选模式下value必须是数组类型,如果组件中没有将selectedUserType初始化为空数组,就会导致值为undefined。另外,selectionChange事件可以直接通过$event获取选中值,或者直接读取绑定的变量。
修正后代码
组件类初始化变量:
selectedUserType: any[] = []; // 必须初始化为数组 filterByCustomFields() { console.log(this.selectedUserType); // 直接读取选中值数组 }
模板代码:
<mat-form-field> <mat-select [(value)]="selectedUserType" multiple (selectionChange)="filterByCustomFields()"> <mat-option *ngFor="let custom of filteredRows" [value]="custom.value"> {{custom.fieldHebKey}} </mat-option> </mat-select> </mat-form-field>
也可以通过事件参数获取:
<mat-select [(value)]="selectedUserType" multiple (selectionChange)="filterByCustomFields($event)">
组件方法:
filterByCustomFields(event: MatSelectChange) { console.log(event.value); // event.value即为选中值数组 }
第二种方式问题分析与修正
第二种实现使用响应式表单,但存在两个错误:
[formControlName]="'customField'"写法错误,应直接写formControlName="customField"(无需方括号和引号);- 组件中未正确初始化对应的
FormControl,且多选模式下初始值必须设为空数组。
修正后代码
组件类初始化表单:
import { FormGroup, FormControl } from '@angular/forms'; // 定义表单组并初始化控件 myForm = new FormGroup({ customField: new FormControl([]) // 初始化为空数组 }); filterByCustomFields(event: MatSelectChange) { console.log(event.value); // 通过事件获取选中值 // 或直接读取表单控件的值 console.log(this.myForm.get('customField')?.value); }
模板代码(需外层包裹form标签并绑定表单组):
<form [formGroup]="myForm"> <mat-form-field> <mat-select formControlName="customField" multiple (selectionChange)="filterByCustomFields($event)"> <mat-option *ngFor="let custom of filteredRows" [value]="custom.value"> {{custom.fieldHebKey}} </mat-option> </mat-select> </mat-form-field> </form>
最佳实现方式
推荐使用修正后的响应式表单方案,它更适合复杂表单场景,能更好地管理表单状态、验证逻辑,且值的获取方式更灵活。如果是简单场景,模板驱动的方案(第一种修正后)也可满足需求。
内容的提问来源于stack exchange,提问作者Kate
相关产品推荐
相关产品推荐

