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

Angular中mat-icon直接传入SVG URL无效?如何在HTML中实现?

解决mat-icon直接在HTML中显示自定义图标的问题

你之前的错误在于把完整的CSS样式规则写进了class属性里——class属性只能填写CSS类名,不能直接写样式声明,所以这种写法完全无效。下面是几种可以直接在HTML中生效的方案:

方案1:内联样式设置背景图

因为内联样式不支持伪元素(content属性仅对伪元素生效),所以改用背景图实现,同时调整尺寸确保图标正常显示:

<mat-icon style="background-image: url('/assets/icons/mdi_list-box-outline.svg'); width: 24px; height: 24px; background-size: contain; background-repeat: no-repeat;"></mat-icon>

方案2:注册Angular Material自定义图标(Angular项目适用)

如果是Angular + Material项目,推荐用官方方式注册自定义图标,后续使用更方便:

  1. 在组件或模块中注入MatIconRegistry和DomSanitizer来注册图标:
import { MatIconRegistry } from '@angular/material/icon';
import { DomSanitizer } from '@angular/platform-browser';

constructor(
  private matIconRegistry: MatIconRegistry,
  private domSanitizer: DomSanitizer
) {
  this.matIconRegistry.addSvgIcon(
    'list-box-outline',
    this.domSanitizer.bypassSecurityTrustResourceUrl('/assets/icons/mdi_list-box-outline.svg')
  );
}
  1. 直接在HTML中引用注册好的图标名称:
<mat-icon>list-box-outline</mat-icon>

方案3:直接在mat-icon内嵌入img标签

最简单直接的方式,无需额外样式或代码:

<mat-icon><img src="/assets/icons/mdi_list-box-outline.svg" style="width: 24px; height: 24px;"></mat-icon>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 16:25:05