如何刷新 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;
  });
}

This works only first time. But when you try to change icon selectedIcon changes, but UI doesn't refresh element 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;
  });
}

This also works only first time.


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);
}

That doesn't work at all.


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

分辨率

浪费了我很多空闲时间来研究如何解决这个问题。用 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>`;
  });
}

This solution - on every icon selection's changing <div> element content (inner html).

我是这样解决这个问题的:

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

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