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

Angular Material v18如何修改字体族?已尝试旧方案无效

Angular Material v18 修改字体族的有效方案

步骤1:确保目标字体已加载

首先需确保要使用的字体(如Open Sans)已被引入到项目中,可以通过在index.html添加字体链接:

<link href="https://fonts.googleapis.com/css2?family=Open+Sans:wght@400;700&display=swap" rel="stylesheet">

或通过SCSS导入本地字体文件。

步骤2:在全局样式文件中配置自定义排版

在项目的全局样式文件(通常为styles.scss)中,按照以下方式配置:

// 导入Angular Material的SCSS模块
@use '@angular/material' as mat;

// 定义自定义排版配置,核心是设置$font-family
$custom-typography: mat.define-typography-config(
  $font-family: 'Open Sans', sans-serif,
  // 可选:根据需求调整各级别文本的字号、行高、字重
  $body-1: mat.define-typography-level(16px, 24px, 400),
  $headline-1: mat.define-typography-level(96px, 112px, 300)
);

// 将核心排版样式应用到根元素
:root {
  @include mat.core-typography($custom-typography);
}

// 为所有Material组件应用自定义排版
@include mat.all-component-typographies($custom-typography);

结合主题色配置(可选)

如果需要同时配置主题颜色和自定义字体,可将排版配置传入主题定义:

// 定义主题颜色配置
$custom-color-config: mat.define-color-config(
  $primary: mat.define-palette(mat.$indigo-palette),
  $accent: mat.define-palette(mat.$pink-palette)
);

// 整合颜色与排版配置生成主题
$custom-theme: mat.define-theme(
  $color-config: $custom-color-config,
  $typography-config: $custom-typography
);

// 应用完整主题样式
:root {
  @include mat.core-theme($custom-theme);
  @include mat.all-component-themes($custom-theme);
}

关键说明

  • Angular Material v18 使用mat.define-typography-config作为全局排版配置的入口,$font-family是控制全局字体族的核心参数。
  • 必须通过mat.core-typography将排版样式注入到全局根元素,同时通过mat.all-component-typographies确保所有Material组件应用该字体。

内容的提问来源于stack exchange,提问作者Alaksandar Jesus Gene

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 15:53:17