首页 > 解决方案 > 角度,无法使用 [svgIcon]="lItem.svgIcon" 动态加载自定义 mat-icon

问题描述

使用角度 8,我无法动态加载自定义 svgIcon。

描述

进入我的component.html我有

      <div *ngFor="let lItem of node.nodeInformationsArray" class="itemDetails" [class]="lItem.cssClass">
          <button mat-icon-button *ngIf="lItem.hasOwnProperty('icon') || lItem.hasOwnProperty('svgIcon')" aria-hidden="false"
          class="material-icons-outlined" [matTooltip]="lItem.tooltip">
          <mat-icon *ngIf="lItem.icon">{{lItem.icon}}</mat-icon>
          <mat-icon *ngIf="lItem.svgIcon" [svgIcon]="lItem.icon"></mat-icon>
          <span *ngIf="lItem.txt" class="itemTxt">{{lItem.txt}}</span>
        </button>
      </div>

在此代码中,试图角材质图标和自定义图标提供通用解决方案,我试图避免解决方案和线条,但如果我在 ng 材质图标路径svgIcon的 innerHtml 中指定,我会在控制台上出现错误。mat-icon

<mat-icon *ngIf="lItem.svgIcon" svgIcon="inverter"></mat-icon>

因此,我尝试同时添加lItem.iconlItem.svgIcon 静态工作(在我的情况下,'inverter' 作为.ts构造函数上的注册图标,它告诉我注册、url 等不是这里的问题。请注意,

<mat-icon *ngIf="lItem.svgIcon" svgIcon="{{lItem.icon}}"></mat-icon>

也不行。

我的梦想和希望

      <div *ngFor="let lItem of node.nodeInformationsArray" class="itemDetails" [class]="lItem.cssClass">
          <button mat-icon-button *ngIf="lItem.hasOwnProperty('icon') || lItem.hasOwnProperty('svgIcon')" aria-hidden="false"
          class="material-icons-outlined" [matTooltip]="lItem.tooltip">
          <mat-icon *ngIf="lItem.icon">{{lItem.icon}}</mat-icon>
          <span *ngIf="lItem.txt" class="itemTxt">{{lItem.txt}}</span>
        </button>
      </div>

使用自定义 svgIcons 和角度材质图标,只需将我的自定义图标注册到我的构造函数中

标签: angularsvgangular-material

解决方案


您可以将自定义图标注册为素材图标。

import { NgModule } from "@angular/core";
import { MatIconModule, MatIconRegistry } from "@angular/material/icon";
import { DomSanitizer } from "@angular/platform-browser";

@NgModule({
  exports: [MatIconModule]
})
export class DemoMaterialModule {
  customIcons: Array<[string, string]> = [["hat", "assets/hat.svg"]];
  constructor(iconRegistry: MatIconRegistry, sanitizer: DomSanitizer) {
    this.customIcons.forEach(([iconName, iconPath]) => {
      iconRegistry.addSvgIcon(
        iconName,
        sanitizer.bypassSecurityTrustResourceUrl(iconPath)
      );
    });
  }
}

模板:

<mat-icon svgIcon="hat"></mat-icon>

与动态变量一起使用:

<!-- hatName = 'hat' -->
<mat-icon [svgIcon]="hatName"></mat-icon>

Stackblitz 上的演示

需要注意的重要事项

hatName必须是对应于自定义svgIcon 名称而不是路径的字符串!


推荐阅读