从单个 svg 文件注册多个 svg 图标 mat-icons

Kho*_*Phi 5 svg angular-material google-material-icons

这是当前注册自定义 svg 图标的图标服务

export class IconService {
  constructor(
    private matIconRegistry: MatIconRegistry,
    private domSanitizer: DomSanitizer
  ) {}

  public registerIcons(): void {
    this.loadIcons(Object.values(Icons), '../assets/icons');
  }

  private loadIcons(iconKeys: string[], iconUrl: string): void {
    iconKeys.forEach((key) => {
      this.matIconRegistry.addSvgIcon(
        key,
        this.domSanitizer.bypassSecurityTrustResourceUrl(
          `${iconUrl}/${key}.svg`
        )
      );
    });
  }
}
Run Code Online (Sandbox Code Playgroud)

我没有为每个文件加载 svg,而是使用这种语法将所有 svg 放入一个文件夹中

my-icons.svg

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
  <symbol id="icon_id">
  ...
  </symbol>
</svg>
Run Code Online (Sandbox Code Playgroud)

我希望能够做类似的事情:

...
    this.matIconRegistry.addSvgIcon(
        key,
        this.domSanitizer.bypassSecurityTrustResourceUrl(
          `${iconUrl}/my-icons.svg#${key}`
        )
      );
...
Run Code Online (Sandbox Code Playgroud)

其中每个key都是指向文件<symbol id="icon_id">...中的idmy-icons.svg

Dan*_*Waw 3

你不能做你想做的事,但你可以这样做:

this.matIconRegistry.addSvgIconSet(
      this.domSanitizer.bypassSecurityTrustResourceUrl("icon_url.svg")
    );
Run Code Online (Sandbox Code Playgroud)

您将按 id 使用图标,如下所示:

<mat-icon svgIcon="id_of_symbol_in_icon_url_svg_file"></mat-icon>
Run Code Online (Sandbox Code Playgroud)