如何更好使用 ng-zorro-antd 圖標

自 ng-zorro-antd 1.7.x 以後圖標發生破壞性變更,雖然帶了諸多優勢,同時也帶來幾個劣勢:

  • 若採用動態加載會產生額外的HTTP請求
  • 若靜態加載需要逐一註冊圖標
  • st 組件的 format 參數無法直接指定圖標

ng-alain 默認使用靜態加載的做法,畢竟後端使用圖標相對於比較有限,即使將 svg 都打包進腳本相比較之前整個 styles 體積上是所有減少,但比較並不多。

而針對以上問題,ng-alain 提供幾種方案。

使用icon插件(推薦)

儘可能從項目中分析並生成靜態 Icon,插件會自動在 src 目錄下生成兩個文件:

  • src/style-icons.ts 自定義部分無法解析(例如:遠程菜單圖標)
  • src/style-icons-auto.ts 命令自動生成文件

自動排除 ng-zorro-antd@delon 已經加載的圖標。

ng g ng-alain:plugin icon

同時,需要手動在 startup.service.ts 中導入:

import { ICONS_AUTO } from '../../../style-icons-auto';
import { ICONS } from '../../../style-icons';

@Injectable()
export class StartupService {
  constructor(iconSrv: NzIconService) {
    iconSrv.addIcon(...ICONS_AUTO, ...ICONS);
  }
}

有效語法

<i class="anticon anticon-user"></i>
<i class="anticon anticon-question-circle-o"></i>
<i class="anticon anticon-spin anticon-loading"></i>
<i nz-icon class="anticon anticon-user"></i>
<i nz-icon type="align-{{type ? 'left' : 'right'}}"></i>
<i nz-icon [type]="type ? 'menu-fold' : 'menu-unfold'" [theme]="theme ? 'outline' : 'fill'"></i>
<i nz-icon [type]="type ? 'fullscreen' : 'fullscreen-exit'"></i>
<i nz-icon type="{{ type ? 'arrow-left' : 'arrow-right' }}"></i>
<i nz-icon type="filter" theme="outline"></i>
<nz-input-group [nzAddOnBeforeIcon]="focus ? 'anticon anticon-arrow-down' : 'anticon anticon-search'"></nz-input-group>

動態加載

動態加載,這是爲了減少包體積而提供的方式。當 NG-ZORRO 檢測用戶想要渲染的圖標還沒有靜態引入時,會發起 HTTP 請求動態引入。你只需要配置 angular.json 文件:

{
  "assets": [
    {
      "glob": "**/*",
      "input": "./node_modules/@ant-design/icons-angular/src/inline-svg/",
      "output": "/assets/"
    }
  ]
}

動態使用

不管是靜態或動態加載,依然無法解決原始方法 class="anticon anticon-" 的便利性,畢竟字符串就是字符串並非 Angular 模板無法被解析,而針對這個問題,提供兩種解決辦法。

類樣式

事實上所有 Antd 圖標都可以在 iconfont 找得到,可以點選自己需要的圖標並生成相應的 css 文件或 cdn,最後在項目中可以直接使用 1.7.0 之前的寫法。

注意: 在項目編輯里加上 anticon anticon- 前綴才能同之前的類名保持一致。

// angular.json
"styles": [
  "src/iconfont.css"
],

如果非cnd還需要將相應的 icon 圖標文件複製到 assets 目錄下,同時修改 iconfont.css@font-face 對應的 url 路徑。

@angular/elements

動態加載的另一種方式是使用 @angular/elements,只需要 nz-icon 指令重新封裝成組件。

import { Component, Input } from '@angular/core';

@Component({
  selector: 'nz-icon',
  template: `<i nz-icon [type]="type"></i>`,
})
export class IconComponent {
  @Input()
  type: string;
}

同時在根模塊裏註冊它。

import { createCustomElement } from '@angular/elements';

@NgModule({
  declarations: [],
  entryComponents: []
})
export class AppModule {
  constructor(injector: Injector) {
    customElements.define('nz-icon', createCustomElement(IconComponent, { injector }));
  }
}

最後。

@Component({
  selector: 'app-demo',
  template: `
  <div [innerHTML]="value"></div>
  `,
})
export class DemoComponent {

  constructor(private san: DomSanitizer) { }

  value = this.san.bypassSecurityTrustHtml(
    `icon: <nz-icon type="bell"></nz-icon>`,
  );
}

結論

本文只是針對這一次 ng-zorro-antd 圖標上的變更做一個總結,就我個人而言還是比較推薦靜態加載的方式,這無關乎包體大小的問題,而是更加明確我需要什麼所以我應加載什麼。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章