Angular Material 中mat-icon使用svg图标,避坑

本文档介绍了如何在Angular Material中使用SVG图标,包括直接注册SVG字符串和从文件路径加载。文章提到了两个常见问题:1. SVG图标文件路径需从assets开始;2. 使用HttpClientModule来读取本地文件,虽然看似多余但实为必要。作者通过示例代码详细展示了注册SVG图标的步骤,并分享了在Stackblitz上遇到的陷阱和解决方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Material默认的icon比较少,而且也没看到官方的网站,我只找到一个可以用的:

Mat-Icon List : 900+ Angular Material Icons (angularjswiki.com)

但是有的地方就需要使用SVG图标

官方也是支持的,只是多了一步:把svg图标注册一下即可使用,也算是简单:

html(aria算是无障碍阅读,不影响)

<mat-icon svgIcon="thumbs-up" aria-hidden="false" aria-label="Example thumbs up SVG icon"></mat-icon>

ts

import {Component} from '@angular/core';
import {DomSanitizer} from '@angular/platform-browser';
import {MatIconRegistry} from '@angular/material/icon';

const THUMBUP_ICON = `
  <svg xmlns="http://www.w3.org/2000/svg" width="24px" height="24px">
    <path d="M0 0h24v24H0z" fill="none"/>
    <path d="M1 21h4V9H1v12zm22-11c0-1.1-.9-2-2-2h-6.31l.95-4.57.03-.32c0-.41-.17-.79-.` +
      `44-1.06L14.17 1 7.59 7.59C7.22 7.95 7 8.45 7 9v10c0 1.1.9 2 2 2h9c.83 0 1.54-.5` +
      `1.84-1.22l3.02-7.05c.09-.23.14-.47.14-.73v-1.91l-.01-.01L23 10z"/>
  </svg>
`;

/**
 * @title SVG icons
 */
@Component({
  selector: 'icon-svg-example',
  templateUrl: 'icon-svg-example.html',
})
export class IconSvgExample {
  constructor(iconRegistry: MatIconRegistry, sanitizer: DomSanitizer) {
    // Note that we provide the icon here as a string literal here due to a limitation in
    // Stackblitz. If you want to provide the icon from a URL, you can use:
    // `iconRegistry.addSvgIcon('thumbs-up', sanitizer.bypassSecurityTrustResourceUrl('icon.svg'));`
    iconRegistry.addSvgIconLiteral('thumbs-up', sanitizer.bypassSecurityTrustHtml(THUMBUP_ICON));
  }
}

这个是官方的示例,也在注释里面说了,要是想用svg'文件,可以直接使用上面这行被注释的代码

iconRegistry.addSvgIcon('thumbs-up', sanitizer.bypassSecurityTrustResourceUrl('icon.svg'));

这里就隐藏两个坑了:

1. 文件的路径从assets开始

2.需要在app.module.ts导入HttpClientModule

import { HttpClientModule } from '@angular/common/http';

坑1可以理解,至少需要定位文件嘛,但是在stackblitz代码演示的时候也不写好,就有点奇怪了。

坑2就不太能理解了,明明是读取本地的文件,为什么还要http组件呢?而且示例里面也没有写,我还以为控制台提示要引入HttpClientModule是在讲其他的问题,抱着试一试的态度,居然好了,我就???

在此记录

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值