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

为什么Angular中matTooltip属性内的换行符\n不生效?

matTooltip 换行符\n失效解决方案

失效原因

Angular Material 的 matTooltip 组件默认对提示内容设置了 white-space: nowrap 样式规则,会自动忽略文本中的换行符 \n 和连续空格,所以直接拼接 \n 无法实现换行效果。

解决方案1:修改样式适配换行符(最简便)

通过修改 tooltip 内容的 white-space 属性为 pre-line 或 pre-wrap 即可识别 \n 换行,可根据需求选择全局生效或单个组件生效:

全局生效

在项目全局样式文件 styles.css/styles.scss 中添加以下代码,适配新旧版本Angular Material:

/* 兼容Angular Material 15+ MDC版本 */
.mat-mdc-tooltip-content {
  white-space: pre-line;
}
/* 兼容Angular Material 15以下旧版本 */
.mat-tooltip {
  white-space: pre-line;
}

修改后你原有的 \n 拼接代码无需改动即可正常实现换行。

单个组件生效(避免全局样式污染)

如果不希望修改全局所有tooltip的样式,可通过自定义类单独指定:

  1. 在当前组件的样式文件中添加代码:
::ng-deep .line-break-tooltip .mat-mdc-tooltip-content,
::ng-deep .line-break-tooltip .mat-tooltip {
  white-space: pre-line;
}
  1. 在使用matTooltip的元素上添加matTooltipClass属性指定自定义类:
<mat-icon 
  [matTooltip]="'Date/Time: ' + row.Date + '\n' + '\nVersion: ' + row.Version"
  matTooltipClass="line-break-tooltip"
>info</mat-icon>

解决方案2:使用自定义tooltip模板(适合复杂内容)

如果提示内容需要更复杂的排版、样式或者嵌入其他元素,可使用Angular Material提供的自定义模板功能:

<ng-template #versionTooltip let-row="row">
  <div>Date/Time: {{row.Date}}</div>
  <div style="margin: 8px 0;"></div>
  <div>Version: {{row.Version}}</div>
</ng-template>

<mat-cell *matCellDef="let row">
  <div style="min-width: 100px;">{{row.Status}}</div> 
  <div *ngIf="row.Date!=null" style="margin-left: 70px;">
    <mat-icon [matTooltip]="versionTooltip" [matTooltipData]="{row: row}">info</mat-icon>
  </div> 
</mat-cell>

注意:该方案不需要额外修改换行相关样式,可直接通过HTML标签实现排版效果。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 16:06:00