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
相关产品推荐
相关产品推荐

