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

Angular 10+Angular Material下拉框选中显示缩写,展开保留全称

解决Angular Material下拉框选中显示缩写、展开显示全称的问题

核心思路是利用Angular Material Select的displayWith属性,自定义选中项的显示文本,同时保持下拉列表显示全称。以下是具体修改步骤:

1. 修正组件类代码

添加一个用于格式化选中项显示的函数,保留原有数据结构:

hi: any;
stateList = [
  {full:'Ohio', short: 'OH'},
  {full:'Minnesota', short:'MN'},
  {full: 'California', short: 'CA'}
];

// 自定义选中项的显示文本
displayFn(state: any): string {
  // 选中项存在时返回缩写,否则返回空字符串
  return state ? state.short : '';
}

2. 修改HTML模板代码

  • 修正循环变量错误(原代码中循环变量type被误写为state)
  • 给mat-select添加[displayWith]属性绑定自定义函数
  • mat-option的[value]绑定整个state对象,确保能获取到缩写字段
<section *ngFor="let row of dataSource; let i = index">
  <div class="column-state">
    <mat-select 
      placeholder="Choose State" 
      [(ngModel)]="row.state" 
      [displayWith]="displayFn"
    >
      <mat-option [value]="type" *ngFor="let type of stateList">
        {{ type.full }}
      </mat-option>
    </mat-select>
  </div>
</section>

原理说明

  • 下拉列表展开时,mat-option始终显示type.full(州的全称)
  • 选中某一项后,ngModel存储对应的state对象,displayWith指定的displayFn函数返回该对象的short属性,因此下拉框显示缩写
  • 再次展开下拉列表时,选项依然显示全称,完全匹配需求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 19:07:36