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

如何让Mat-Select选中后的选项保留多行格式化样式?

实现方案

mat-select默认会提取选中选项的纯文本内容渲染到选择框触发区,不会保留mat-option内部自定义的DOM结构和类名,因此会出现内容合并为单行、样式统一的问题,使用官方提供的mat-select-trigger自定义触发区内容即可实现需求,步骤如下:

  • 第一步:修改模板代码,在mat-select内新增mat-select-trigger节点,单独编写选中状态下要展示的结构,和下拉选项的结构保持一致即可
<mat-select [(value)]="selected">
  <!-- 自定义选中状态的展示内容 -->
  <mat-select-trigger>
    <p class="title">{{ selected?.title }}:</p>
    <p class="description">{{ selected?.Description }}</p>
  </mat-select-trigger>

  <mat-option *ngFor="let Option of Options" [value]="Option">
    <p class="title">{{ Option.title}}:</p>
    <p class="description">{{ Option.Description}}</p>
  </mat-option>
</mat-select>

模板里的?.是Angular安全导航符,用于避免组件初始化阶段selected未赋值时抛出空值错误

  • 第二步:补充对应样式,覆盖mat-select触发区默认的单行限制,让自定义的多行结构正常展示
/* 穿透Angular视图封装,修改Material组件内部样式 */
::ng-deep .mat-select-trigger {
  height: auto;
  padding: 6px 0;
  white-space: normal;
  line-height: 1.4;
}

/* 标题、描述样式和下拉面板内的样式保持统一即可 */
.title {
  margin: 0;
  font-size: 14px;
  font-weight: 600;
}
.description {
  margin: 2px 0 0 0;
  font-size: 12px;
  font-weight: 400;
  color: #6b7280;
}
  • 补充说明
    • 如果使用mat-select的多选模式,只需要在mat-select-trigger内遍历选中值数组,按相同结构渲染每一项即可
    • 该方案是Angular Material官方提供的自定义能力,不会随版本迭代出现兼容性问题,不建议通过强行修改组件内部DOM的方式实现需求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.01 20:33:40