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

Angular Material Select组件值变更调用函数问题求助

Angular Material Select 值变更触发函数问题解决

问题场景

之前用原生HTML select组件时,通过(change)事件能正常调用getRequests()函数:

原生TS代码

selected = "pending";
  
getRequests(event: any) {
  this.selected = event.target.value;
  if(this.selected=="pending")
    console.log("Inside Pending Requests")
  else
    console.log("Inside Granted Requests")
}

原生HTML代码

<div style="margin-left: 70%;" appearance="fill">
  <select (change)="getRequests($event)">
    <option value="pending">Pending</option>
    <option value="granted">Granted</option>
  </select>
</div>

换成Angular Material的mat-select后,原有的(change)事件无法触发函数:

当前mat-select代码

<mat-form-field style="margin-left: 70%;" appearance="fill">
<mat-label>Status</mat-label>
<mat-select [(value)]="selected" (change)="getRequests($event)" >
  <mat-option value="pending">Pending</mat-option>
  <mat-option value="granted">Granted</mat-option>
</mat-select>

解决方案

Angular Material的mat-select组件不使用原生(change)事件,而是提供了专属的(selectionChange)事件来监听选项变更,修改方式如下:

1. 修改HTML模板

将(change)替换为(selectionChange):

<mat-form-field style="margin-left: 70%;" appearance="fill">
  <mat-label>Status</mat-label>
  <mat-select [(value)]="selected" (selectionChange)="getRequests($event)">
    <mat-option value="pending">Pending</mat-option>
    <mat-option value="granted">Granted</mat-option>
  </mat-select>
</mat-form-field>

2. 调整TS函数(可选优化)

selectionChange事件返回的是MatSelectChange类型对象,直接通过event.value就能获取选中值,同时需要导入对应类型:

import { MatSelectChange } from '@angular/material/select';

selected = "pending";

getRequests(event: MatSelectChange) {
  this.selected = event.value;
  if (this.selected === "pending") {
    console.log("Inside Pending Requests");
  } else {
    console.log("Inside Granted Requests");
  }
}

3. 进一步简化(利用双向绑定)

因为已经通过[(value)]="selected"实现了双向绑定,选中值会自动同步到this.selected,所以可以省略事件参数,直接使用组件内的selected变量:

selected = "pending";

getRequests() {
  if (this.selected === "pending") {
    console.log("Inside Pending Requests");
  } else {
    console.log("Inside Granted Requests");
  }
}

对应的HTML模板修改为:

<mat-select [(value)]="selected" (selectionChange)="getRequests()">

内容的提问来源于stack exchange,提问作者Amateur coder

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 05:40:33