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

Angular 17与Material 17中$font-family变量未定义问题求助

解决Angular Material主题中$font-family未定义错误

常见原因及修复方案

1. 导入顺序错误

Angular Material的核心变量和混合宏必须在自定义主题配置前导入,否则无法识别$font-family这类内置参数。根据你的Angular Material版本选择对应导入方式:

新版(v14+,使用@use语法)

// 先导入Material核心模块并启用
@use '@angular/material' as mat;
@include mat.core();

// 此时可直接在排版配置中使用$font-family参数
$custom-typography: mat.define-typography-config(
  $font-family: 'Roboto, "Helvetica Neue", sans-serif'
);

// 后续主题定义
$primary: mat.define-palette(mat.$indigo-palette);
$theme: mat.define-light-theme((
  color: (primary: $primary),
  typography: $custom-typography
));

@include mat.all-component-themes($theme);

旧版(v13及以下,使用@import语法)

// 先导入Material主题基础文件
@import '@angular/material/theming';
@include mat-core();

// 使用$mat-font-family或自定义变量
$custom-font: 'Roboto, sans-serif';
$custom-typography: mat-typography-config($font-family: $custom-font);

2. 版本差异导致变量名变更

不同版本的Angular Material对排版参数的命名有区别:

  • v14+:直接在mat.define-typography-config中使用$font-family参数
  • 旧版本:需使用$mat-font-family作为内置变量,或自行定义后传入mat-typography-config

3. 自定义变量未提前声明

如果$font-family是你自己定义的变量,必须确保它在使用前被声明:

@use '@angular/material' as mat;

// 提前声明自定义字体变量
$font-family: 'Your Custom Font, sans-serif';

@include mat.core();

$custom-typography: mat.define-typography-config(
  $font-family: $font-family
);

4. 全局样式未正确引入主题文件

检查angular.json的styles数组,确保你的_theme.scss(或引用它的全局样式文件)被正确配置,避免变量作用域局限在局部组件中。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 07:33:22