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

如何让Angular的<mat-select>显示用户输入的文本?

解决mat-select嵌入输入框后显示输入内容的问题

你当前的代码里,输入框绑定的holdReason和mat-select绑定的textList是两个独立变量,所以输入内容不会同步到选择框的显示值。要实现回车后让mat-select显示输入的文本,可以通过以下两种方式实现:

方式一:动态添加选项并选中

这种方式会把用户输入的内容添加到选项列表中,同时设置为选中状态:

组件类逻辑

textList: any;
list: string[] = ['原有选项1', '原有选项2'];
holdReason: string = '';

onInputEnter() {
  // 避免添加空内容
  if (!this.holdReason.trim()) return;
  // 将输入内容添加到选项列表
  this.list.push(this.holdReason);
  // 设置mat-select的选中值为输入内容
  this.textList = this.holdReason;
  // 清空输入框(可选操作)
  this.holdReason = '';
}

模板代码

<mat-select [(ngModel)]="textList">
  <mat-option *ngFor="let text of list" [value]="text">
    {{ text }}
  </mat-option>
                
  <mat-form-field class="example-full-width">
    <input matInput [(ngModel)]="holdReason" (keyup.enter)="onInputEnter()"/>
  </mat-form-field>
</mat-select>

方式二:直接绑定输入值到选中状态(不添加到选项列表)

如果不需要把输入内容保留到选项列表,仅临时显示输入值,可以直接在回车时将输入值赋值给mat-select的绑定变量,同时添加一个匹配输入值的临时选项:

模板代码

<mat-select [(ngModel)]="textList">
  <mat-option *ngFor="let text of list" [value]="text">
    {{ text }}
  </mat-option>
  
  <!-- 临时选项,仅当输入框有内容时显示 -->
  <mat-option [value]="holdReason" *ngIf="holdReason.trim()">
    {{ holdReason }}
  </mat-option>
                
  <mat-form-field class="example-full-width">
    <input matInput [(ngModel)]="holdReason" (keyup.enter)="textList = holdReason"/>
  </mat-form-field>
</mat-select>

说明

  • 两种方式都通过监听输入框的keyup.enter事件触发逻辑,确保回车后同步输入内容到mat-select的选中值。
  • 可以根据需求选择是否将输入内容添加到选项列表中。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 21:01:04