簡體   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