繁体   English   中英

如何刷新 Angular 上的 Font Awesome 图标?

[英]How to refresh Font Awesome icon on Angular?

有没有办法动态更改字体真棒图标? 我希望用户能够动态地使用 select 字体真棒图标之一。 仅当您第一次添加 class 时才有效。 我尝试做的地方是 - MatDialog 用户必须使用 select 图标、背景颜色和类别名称的形式。 对于 select 图标用户应该打开另一个对话框。

在此处输入图像描述 在此处输入图像描述

我正在使用Angular 9.1.4Font Awesome 5.13.0


这就是我尝试过的:

1.使用ngClass

类别-dialog.component.html

<div [ngStyle]="selectedColor">
    <i [ngClass]="selectedIcon"></i>
</div>

类别-dialog.component.ts

openIconDialog(): void {
  const dialogRef = this.dialog.open(DialogIconSelectComponent, { width: '15rem' });
  dialogRef.afterClosed().subscribe(result => {
    this.selectedIcon = result;
  });
}

这仅适用于第一次。 但是当您尝试更改图标selectedIcon更改时,UI 不会刷新元素 class。


2. 使用@ViewChild

@ViewChild('iconElement') iconElement: ElementRef;

constructor(private dialog: MatDialog,
            private renderer: Renderer2) { }

openIconDialog(): void {
  const dialogRef = this.dialog.open(DialogIconSelectComponent, { width: '15rem' });
  dialogRef.afterClosed().subscribe((result: string) => {
    this.iconElement.nativeElement.className = result;
  });
}

这也只适用于第一次。


3. 使用@ViewChild 和 Renderer2

类别-dialog.component.html

<div #colorElement [ngStyle]="selectedColor">
    <i #iconElement></i>
</div>

类别-dialog.component.ts

@ViewChild('colorElement') parentElement: ElementRef;
@ViewChild('iconElement') childElement: ElementRef;

constructor(private dialog: MatDialog,
            private renderer: Renderer2) { }

openIconDialog(): void {
  const dialogRef = this.dialog.open(DialogIconSelectComponent, { width: '15rem' });
  dialogRef.afterClosed().subscribe(result => {
    this.replaceIcon(result);
  });
}

replaceIcon(iconClass: string): void {
  const i = this.renderer.createElement('i');
  this.renderer.setProperty(i, 'class', iconClass);
  this.renderer.removeChild(this.parentElement.nativeElement, this.childElement);
  this.renderer.appendChild(this.parentElement.nativeElement, i);
}

那根本行不通。


有什么办法可以动态更改字体真棒?

解析度

浪费了我很多空闲时间来研究如何解决这个问题。 Renderer2和所有肮脏的 Javascript 方法尝试了一切。 但是有一天我想出了使用innerHtml的想法。

渲染内部 HTML 的新字符串以交互方式更改 Font Awesome 图标。

类别-dialog.component.html

<div [ngStyle]="selectedColor" [innerHtml]="selectedIconHtml"></div>

类别-dialog.component.ts

openIconDialog(): void {
  const dialogRef = this.dialog.open(DialogIconSelectComponent, { width: '15rem' });
  dialogRef.afterClosed().subscribe((result: string) => {
    // EVERY TIME NEW ELEMENT WITH NEW FA CLASS
    this.selectedIconHtml = `<i class="${result}"></i>`;
  });
}

此解决方案 - 在每个图标选择的更改<div>元素内容(内部 html)上。

我这样解决了这个问题:

<div innerHTML="<i class='{{icon}}'></i>">
</div>

在这种情况下,图标将在值更改后重新渲染。 innerHTML使这很容易发生。 TS 文件中不需要任何代码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM