Angular自定义主题无法修改字体样式问题排查
问题分析与解决方案
你的问题出在三个关键点上,逐一修正即可解决字体不生效的问题:
1. 字体家族的语法错误
你在定义$my-typography时,把字体列表写成了单个字符串:
$font-family: 'Noto Sans, sans-serif', // 错误:整个字符串被视为一个字体名称
浏览器会把'Noto Sans, sans-serif'当作一个完整的字体名,找不到这个字体时就会直接回退到系统默认的sans-serif(即Arial)。正确写法应该是将字体分开:
$font-family: 'Noto Sans', sans-serif,
2. 自定义排版未传入mat.core()
mat.core()混合宏负责生成全局的.mat-typography样式,默认使用Roboto字体。你需要把自定义的排版配置传入这个宏,才能覆盖全局类的字体设置:
修改theme.scss的顺序,先定义排版,再传入mat.core():
@use '@angular/material' as mat; // 先定义自定义排版 $my-typography: mat.define-typography-config( $font-family: 'Noto Sans', sans-serif, ); // 将自定义排版传入core,覆盖全局.mat-typography @include mat.core($my-typography); // 后续的调色板和主题定义不变 $my-palette-primary: mat.define-palette(mat.$indigo-palette); $my-palette-accent: mat.define-palette(mat.$green-palette); $my-palette-warn: mat.define-palette(mat.$red-palette); $my-theme: mat.define-light-theme(( color: ( primary: $my-palette-primary, accent: $my-palette-accent, warn: $my-palette-warn, ), typography: $my-typography, )); @include mat.all-component-themes($my-theme);
3. 检查是否残留默认预构建主题
如果你的项目中还导入了Angular Material的默认预构建主题(indigo-pink.css),它会覆盖你的自定义主题样式,导致.mat-typography仍使用Roboto:
- 打开
styles.scss,确保没有以下导入语句:@import '@angular/material/prebuilt-themes/indigo-pink.css'; // 删除这行 - 打开
angular.json,检查styles数组,确保没有包含@angular/material/prebuilt-themes/indigo-pink.css,只保留你的自定义主题或styles.scss:"styles": [ "src/styles.scss" ]
完成以上修正后,重新启动项目,浏览器中的.mat-typography类就会使用Noto Sans字体了。
内容的提问来源于stack exchange,提问作者VBobCat
相关产品推荐
相关产品推荐

