gpt4 book ai didi

Angular ,无法使用 [svgIcon] ="lItem.svgIcon"动态加载自定义 mat-icon

转载 作者:行者123 更新时间:2023-12-05 07:15:46 25 4
gpt4 key购买 nike

使用 angular 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>

在这段代码中,试图为这两个 angular material icons 找到一个共同的解决方案和自定义图标,我试图避免 svgIcon 解决方案和行,但是如果我在 mat-icon 的 innerHtml 中指定 ng Material 图标的路径,我会在控制台上收到错误.

<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 和 Angular 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>

Demo在 Stackblitz 上

注意事项

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

关于 Angular ,无法使用 [svgIcon] ="lItem.svgIcon"动态加载自定义 mat-icon,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59513368/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com