如何在Angular中使用Material Icons Symbols?设置fontSet属性遇阻
解决Angular里MatIcon渲染Material Icons Symbols的问题
为啥会出问题
MatIcon组件的fontSet属性默认是适配旧版Material Icons字体的,而新版Material Icons Symbols用的是material-symbols-outlined这类类名,两者的映射不匹配,直接设fontSet="material-icons-outlined"没法触发符号字体的样式,所以显示不对。
三种解决办法
办法一:直接用fontFamily加类名
不用纠结fontSet,直接给MatIcon加符号字体的类名,同时指定字体族:
<mat-icon class="material-symbols-outlined" fontFamily="Material Symbols Outlined"> expand_content </mat-icon>
办法二:注册自定义字体集
在你的App模块里,通过MatIconRegistry把符号字体的类名注册成MatIcon能识别的fontSet:
import { NgModule } from '@angular/core'; import { MatIconModule, MatIconRegistry } from '@angular/material/icon'; @NgModule({ imports: [MatIconModule] }) export class AppModule { constructor(iconRegistry: MatIconRegistry) { // 把material-symbols-outlined注册成可识别的fontSet iconRegistry.registerFontClassAlias('material-symbols-outlined', 'material-symbols-outlined'); } }
注册完之后就能正常用fontSet了:
<mat-icon fontSet="material-symbols-outlined">expand_content</mat-icon>
办法三:全局CSS补规则
在全局样式文件(比如styles.css)里加一段CSS,让MatIcon在指定fontSet时自动应用符号字体的样式:
.mat-icon.material-symbols-outlined { font-family: 'Material Symbols Outlined'; font-weight: normal; font-style: normal; font-size: 24px; line-height: 1; letter-spacing: normal; text-transform: none; display: inline-block; white-space: nowrap; word-wrap: normal; direction: ltr; -webkit-font-feature-settings: 'liga'; -webkit-font-smoothing: antialiased; }
之后直接用fontSet就行:
<mat-icon fontSet="material-symbols-outlined">expand_content</mat-icon>
别忘了检查这个
确保你已经在index.html里正确引入了Material Icons Symbols的字体链接,不然啥办法都白搭:
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@20..48,100..700,0..1,-50..200" />
内容的提问来源于stack exchange,提问作者Ole
相关产品推荐
相关产品推荐

