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

如何获取Angular Material中mat-option选中项的value值

问题原因

你的 mat-select 组件已经通过 [(ngModel)] 双向绑定了TS代码中的formSelect变量,而你定义的traType变量和模板的下拉选择器没有任何关联,因此调用this.traType.value自然返回undefined。

解决方案

方案1(推荐):直接使用双向绑定变量

双向绑定会自动同步下拉框选中值到formSelect变量,你直接读取该变量即可拿到预期结果:

// 直接获取选中值
const selectedTraType = this.formSelect;

方案2:通过视图查询获取组件实例

如果你需要通过组件实例获取值,可以按如下步骤修改:

  1. 给模板中的mat-select添加模板引用变量:
<mat-select
  placeholder="TRA Type"
  id="traType"
  name="traType"
  data-qa="new-tra"
  [(ngModel)]="formSelect"
  #traTypeSelect
  required>
  1. 在TS代码中通过ViewChild查询组件实例后读取值:
import { ViewChild } from '@angular/core';
import { MatSelect } from '@angular/material/select';

export class YourComponent {
  formSelect: string;
  @ViewChild('traTypeSelect') traTypeSelect!: MatSelect;

  // 注意:需要在ngAfterViewInit生命周期之后才能获取到实例
  ngAfterViewInit() {
    console.log(this.traTypeSelect.value);
  }
}

额外检查项

请确认你的功能模块已经导入了必要依赖,否则双向绑定可能无法正常生效:

  • @angular/material/select 下的 MatSelectModule
  • @angular/forms 下的 FormsModule

内容的提问来源于stack exchange,提问作者Jake Castillo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 08:06:05