angular - 角度,无法使用 [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.icon
和lItem.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 和角度材质图标,只需将我的自定义图标注册到我的构造函数中
解决方案
您可以将自定义图标注册为素材图标。
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
名称而不是路径的字符串!
推荐阅读
- java - 这个 hashCode 方法是如何工作的?
- json - 如何通过 csv.DictWriter 将 csv.DictReader JSON 结构写回 TSV 文件?
- node.js - 在使用 async-await 在 nodejs 中渲染模板之前等待 firebase 存储数据库拉取完成
- ansible - 如何循环浏览库存文件?
- azure - ARM 模板是否支持创建 AAD 应用程序/服务主体?
- php - 从 loadHTML 获取 url 时取消链接不起作用
- c# - Xamarin.Forms ListView 在集合更改之前滚动后在 Android 中呈现错误
- python - 如何序列化棉花糖中的元组列表?
- c++ - C++ 使用 for 循环迭代 2 个向量
- python - 如何使用python将包含特定单词的整行excel(.csv)复制到另一个csv文件中?