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

Angular Material 19中启用排版工具类与自定义字体的方法咨询

Angular Material 19中启用排版工具类与自定义字体的方法咨询

看起来你已经在Angular Material 19的新主题API上迈出了不错的第一步,颜色系统正常工作就是个好开头!不过排版工具类和自定义字体的问题确实是新主题API里容易踩的小坑,我来帮你一步步搞定:

一、解决.mat-h1这类排版工具类不生效的问题

在新的主题API中,Material不会自动生成.mat-h1、.mat-body1这类排版工具类样式,你需要手动在主题代码中引入对应的mixin。在你现有的@include mat.theme(...)代码后面,添加上这一行:

@include mat.typography-utilities();

这行代码会直接生成所有Material的排版工具类,之后你就能正常使用这些类来快速设置文本样式了。

二、搞定自定义字体不生效的问题

默认的Times字体跳出来确实头疼,我们分两步来解决:

  1. 先确保自定义字体已正确加载
    你得先把Roboto和Open Sans字体成功引入到项目中。如果是用本地字体文件,就在style.scss最顶部添加@font-face规则(记得替换成你实际的字体文件路径):

    @font-face {
      font-family: 'Roboto';
      src: url('/assets/fonts/Roboto-Light.ttf') format('truetype');
      font-weight: 300;
      font-style: normal;
    }
    @font-face {
      font-family: 'Roboto';
      src: url('/assets/fonts/Roboto-Medium.ttf') format('truetype');
      font-weight: 500;
      font-style: normal;
    }
    @font-face {
      font-family: 'Open Sans';
      src: url('/assets/fonts/OpenSans-Bold.ttf') format('truetype');
      font-weight: 900;
      font-style: normal;
    }
    // 记得补充你需要的其他字重,比如Open Sans的常规字重等
    

    要是你用的是CDN加载字体,直接在index.html的<head>里加对应的引入标签就行,不过要确保字体的字重和你主题配置里的设置匹配。

  2. 让主题的排版配置全局生效
    你已经在主题里设置了自定义字体,但还需要把这些配置应用到全局样式中。在@include mat.typography-utilities();后面再添加上:

    @include mat.typography-base();
    

    这行代码会把你配置的字体、字重等排版规则应用到body以及全局的基础文本样式上,替换掉默认的Times字体。

最后整合你的主题代码

把上面的修改整合后,你的主题SCSS代码大概是这样的:

// 1. 先加载自定义字体
@font-face {
  font-family: 'Roboto';
  src: url('/assets/fonts/Roboto-Light.ttf') format('truetype');
  font-weight: 300;
  font-style: normal;
}
@font-face {
  font-family: 'Roboto';
  src: url('/assets/fonts/Roboto-Medium.ttf') format('truetype');
  font-weight: 500;
  font-style: normal;
}
@font-face {
  font-family: 'Open Sans';
  src: url('/assets/fonts/OpenSans-Bold.ttf') format('truetype');
  font-weight: 900;
  font-style: normal;
}

// 2. 配置并应用主题
@include mat.theme((
  color: (
    primary: mat.$orange-palette,
    tertiary: mat.$magenta-palette,
    theme-type: color-scheme,
  ),
  typography: (
    plain-family: 'Roboto',
    brand-family: 'Open Sans',
    bold-weight: 900,
    medium-weight: 500,
    regular-weight: 300,
  ),
  density: 0,
));

// 3. 启用排版工具类
@include mat.typography-utilities();

// 4. 全局应用自定义排版样式
@include mat.typography-base();

别忘啦,修改完SCSS后最好重启一下Angular开发服务器,有时候缓存会导致样式不及时更新。如果还有问题,可以检查下字体文件路径是否正确、字重配置和加载的字体是否匹配~

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.08 14:48:03