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

如何在mat-card中设置mat-card-title样式实现溢出截断且不使用已废弃::ng-deep

合规替代方案(无需使用已弃用的::ng-deep)

Angular 中针对组件样式无法穿透子组件、默认样式被覆盖的问题,有两种常用的合规实现方式:


方案1:全局样式加限定前缀(更推荐,改动最小)

直接在项目全局样式文件(通常为src/styles.css或src/styles.scss)中添加带自定义类限定的规则,仅作用于你需要修改的mat-card,不会污染全局样式:

  1. 给需要实现截断的mat-card添加自定义类名
<mat-card class="title-trunc-card">
  <mat-card-header>
    <mat-card-title>需要截断的长标题文本</mat-card-title>
  </mat-card-header>
  <!-- 其他card内容 -->
</mat-card>
  1. 在全局样式文件中添加对应规则:
.title-trunc-card .mat-card-title {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 100%; /* 可按需调整为固定宽度,父元素无宽度限制时必须设置 */
}

方案2:修改当前组件视图封装模式

如果不想修改全局样式,可将当前组件的视图封装设置为None,同时所有样式加自定义类前缀避免样式泄露:

  1. 组件ts文件中修改封装配置:
import { Component, ViewEncapsulation } from '@angular/core';

@Component({
  selector: 'app-your-component',
  templateUrl: './your-component.component.html',
  styleUrls: ['./your-component.component.css'],
  encapsulation: ViewEncapsulation.None // 关闭样式封装
})
export class YourComponent { }
  1. 组件css文件中添加规则:
.title-trunc-card .mat-card-title {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 100%;
}

生效排查

如果规则未生效,检查mat-card-title的父级元素是否设置了明确的宽度/最大宽度,块级元素默认会撑满内容宽度,没有宽度限制时溢出截断规则不会触发。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 00:36:07