mat-select搭配material-icons异常:选中选项后显示图标文本
修复Mat-Select选中后额外显示图标文本的问题
这个问题我之前也碰到过!根源在于mat-select默认会把mat-option内部的所有DOM内容(包括Material Icons标签里的文本节点,比如highlight_off)直接同步到选中后的触发显示区域——虽然图标本身是通过CSS隐藏了文本,但默认的内容复制逻辑还是会把这些文本带出来,导致显示异常。
解决方案:用mat-select-trigger自定义选中后的显示内容
通过添加mat-select-trigger,你可以完全控制选中项的显示内容,避免默认的自动复制带来的问题。具体修改如下:
<mat-form-field> <mat-select placeholder="warningtype" [(ngModel)]="selected.warningType" #warning="ngModel" name="warning" > <!-- 自定义选中后的展示区域 --> <mat-select-trigger> <div> <span *ngIf="selected.warningType === WarningType.ERROR"> <i class='material-icons red'>highlight_off</i> </span> <span *ngIf="selected.warningType === WarningType.INFO"> <i class='material-icons blue'>error_outline</i> </span> <span *ngIf="selected.warningType === WarningType.WARNING"> <i class='material-icons orange'>warning</i> </span> {{selected.warningType}} </div> </mat-select-trigger> <!-- 下拉选项保持原逻辑即可 --> <mat-option *ngFor="let warning of warnings" [value]="warning.value"> <div> <span *ngIf="warning.label === WarningType.ERROR"> <i class='material-icons red'>highlight_off</i> </span> <span *ngIf="warning.label === WarningType.INFO"> <i class='material-icons blue'>error_outline</i> </span> <span *ngIf="warning.label === WarningType.WARNING"> <i class='material-icons orange'>warning</i> </span> {{warning.label}} </div> </mat-option> </mat-select> </mat-form-field>
优化建议:避免重复代码
上面的代码里,图标渲染的逻辑在trigger和option里重复了,你可以把这部分抽成一个独立的组件来复用,减少维护成本:
- 创建一个
WarningIconComponent:
import { Component, Input } from '@angular/core'; import { WarningType } from './your-types-file'; // 导入你的WarningType枚举 @Component({ selector: 'warning-icon', template: `<i class='material-icons {{colorClass}}'>{{iconName}}</i>`, styles: [] }) export class WarningIconComponent { @Input() type!: WarningType; get iconName(): string { switch(this.type) { case WarningType.ERROR: return 'highlight_off'; case WarningType.INFO: return 'error_outline'; case WarningType.WARNING: return 'warning'; default: return ''; } } get colorClass(): string { switch(this.type) { case WarningType.ERROR: return 'red'; case WarningType.INFO: return 'blue'; case WarningType.WARNING: return 'orange'; default: return ''; } } }
- 在模板里复用这个组件:
<mat-form-field> <mat-select placeholder="warningtype" [(ngModel)]="selected.warningType" #warning="ngModel" name="warning" > <mat-select-trigger> <div> <warning-icon [type]="selected.warningType"></warning-icon> {{selected.warningType}} </div> </mat-select-trigger> <mat-option *ngFor="let warning of warnings" [value]="warning.value"> <div> <warning-icon [type]="warning.label"></warning-icon> {{warning.label}} </div> </mat-option> </mat-select> </mat-form-field>
这样修改后,选中项的显示就只会展示你想要的图标和文本,不会再出现额外的图标名称文本了。
内容的提问来源于stack exchange,提问作者Alessandro Celeghin
相关产品推荐
相关产品推荐

