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

谭玄天
2023-12-01

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是在讲其他的问题,抱着试一试的态度,居然好了,我就???

在此记录

 类似资料: