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

Angular Material mat-select选中后输入框显示员工姓名问题

解决Angular Material mat-select选中后显示员工姓名的问题

方案1:绑定完整员工对象(推荐)

直接将员工对象作为选项值,后续可直接获取姓名字段:

调整mat-select与mat-option代码

<mat-select formControlName="employeeid" [(ngModel)]="selectedEmployee" (selectionChange)="onChange($event)" [compareWith]="compareEmployee">
  <input style="width: -webkit-fill-available; margin-bottom: 10px; height: 30px;" placeholder="Search & Select"/>
  <div style="height: 200px; overflow-y: auto">
    <mat-option>Select Employee</mat-option>
    <mat-option *ngFor="let item of employeeDropdown" [value]="item">{{ item.firstname }}</mat-option>
  </div>
</mat-select>

修改输入框代码

<mat-form-field appearance="outline" fxFlex="1 1 calc(50% - 10px)" fxFlex.lt-md="1 1 calc(30% - 10px)"
              fxFlex.lt-sm="100%" fxFlex.xs="100%" class="from-color">
  <mat-label class="label-padding">Employee Details</mat-label>
  <input class="label-padding" type="text" matInput placeholder="Employee Details"
      formControlName="firstname" [value]="selectedEmployee?.firstname" required/>
</mat-form-field>

组件类添加对比函数

由于绑定对象,需定义对象对比规则:

compareEmployee(a: any, b: any): boolean {
  return a && b ? a.employeeid === b.employeeid : a === b;
}

组件变量调整

将原selected变量替换为selectedEmployee,用于存储选中的员工对象:

selectedEmployee: any; // 建议替换为你的员工接口类型

方案2:保留ID绑定,通过ID匹配姓名

若不想修改选项值绑定方式,可在选中事件中根据ID查找姓名:

组件类修改onChange方法

onChange(event: any) {
  const selectedId = event.value;
  const targetEmployee = this.employeeDropdown.find(item => item.employeeid === selectedId);
  this.yourFormGroup.get('firstname')?.setValue(targetEmployee?.firstname || '');
}

移除输入框的[value]绑定

通过表单控件自动赋值:

<input class="label-padding" type="text" matInput placeholder="Employee Details"
    formControlName="firstname" required/>

内容的提问来源于stack exchange,提问作者H A S I B

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 20:27:59