Angular Dialog:如何在afterClosed()中同时获取多个mat-form-field的值?
解决方法
问题根源是你把两个mat-select绑定到了同一个FormControl实例options,后一个选择的内容会覆盖前一个,所以最终只能拿到Max的值。要同时获取Min和Max的选择结果,需要为每个选择框单独分配控件,或者用FormGroup统一管理。
步骤1:创建表单组(推荐)
在对话框组件的类中,用FormGroup包装两个独立的FormControl,分别对应Min和Max:
import { FormGroup, FormControl } from '@angular/forms'; // 组件类内部定义 filterForm = new FormGroup({ minNumbers: new FormControl([]), // multiple模式下初始值为空数组 maxNumbers: new FormControl([]) });
步骤2:修改模板绑定
把两个mat-select分别绑定到表单组对应的控件上,同时简化mat-option的value(不需要包装成对象,直接用数字即可):
<mat-form-field appearance="fill"> <mat-label>Min</mat-label> <mat-select [formControl]="filterForm.get('minNumbers')" multiple> <mat-option *ngFor="let number of numbers" [value]="number"> {{ number }} </mat-option> </mat-select> </mat-form-field> <mat-form-field appearance="fill"> <mat-label>Max</mat-label> <mat-select [formControl]="filterForm.get('maxNumbers')" multiple> <mat-option *ngFor="let number of numbers" [value]="number"> {{ number }} </mat-option> </mat-select> </mat-form-field>
步骤3:关闭对话框时传递完整表单值
在对话框的确认逻辑中,把整个表单的值作为返回结果:
// 对话框组件内的确认按钮点击事件 onSubmit() { this.dialogRef.close(this.filterForm.value); }
步骤4:接收并处理返回值
在调用对话框的组件中,就能同时拿到Min和Max的选择结果了:
dialogRef.afterClosed().subscribe((response) => { if (response) { console.log('选中的Min值:', response.minNumbers); console.log('选中的Max值:', response.maxNumbers); } });
内容的提问来源于stack exchange,提问作者George Perid
相关产品推荐
相关产品推荐

