如何将自定义 svg 图标和常规 angular material 图标添加到同一个 mat-icon 标签

How to add custom svg icon and regular angular material icons to same mat-icon tag

使用 Angular 8 material 设计,我被困在需要在同一个垫子上同时使用自定义 svg 图标和 built-in/regular material 图标的地步-图标标签。

我是 运行 一个循环来显示带有这些图标的菜单,其中有一些菜单项。我使用的是常规 material,对于某些菜单项,我必须使用自定义图标 (svg)。

需要这样的东西:

<mat-icon svgIcon="menuIcon">{{menuIcon}}</mat-icon>

通常,我会有 2 个代表菜单项图标的属性:

  • svgIcon 这是 SVG 图标的名称
  • icon 这是 CSS 字体图标的名称

菜单项将使用以下界面表示:

export interface MenuItem {
  /** The menu item's title. */
  title: string;
  /** The menu item's SVG icon. Either this or the `icon` property should be used. */
  svgIcon?: string;
  /** The menu item's icon. Either this or the `svgIcon` property should be used. */
  icon?: string;
  // Other properties
}

然后我会根据是否设置了 svgIconicon 属性有条件地显示适当的 <mat-icon>:

<mat-icon *ngIf="item?.icon && !item?.svgIcon">{{ item.icon }}</mat-icon>
<mat-icon *ngIf="!item?.icon && item?.svgIcon" [svgIcon]="item.svgIcon"></mat-icon>

或者,您可以在界面中使用 isSvgIcon 属性 来表示指定的图标是否为 SVG 图标:

<mat-icon *ngIf="item.isSvgIcon" [svgIcon]="item.icon"></mat-icon>
<mat-icon *ngIf="!item.isSvgIcon">{{ item.icon }}</mat-icon>