在 Angular 中使用 Font Awesome 图标库

首先安装 fontawesome,下面使用yarn安装,也可以使用npm

yarn add @fortawesome/fontawesome-svg-core \
  yarn add @fortawesome/free-solid-svg-icons \
  yarn add @fortawesome/angular-fontawesome

然后编辑 app.module.ts 文件,引入 FontAwesomeModule

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { FontAwesomeModule } from '@fortawesome/angular-fontawesome';
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FontAwesomeModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

接着在 app.component.ts 文件中,引入我们要使用的图标

import { Component } from '@angular/core';
import { faCoffee } from '@fortawesome/free-solid-svg-icons';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
  faCoffee = faCoffee;
}

上面的例子引入了 coffee 图标,然后就可以在模板中使用

<div style="text-align:center">
  <fa-icon [icon]="faCoffee"></fa-icon>
</div>

说明

其实我很不喜欢fontawesome 5+,因为它把图标分成了好几类,我们刚才只安装了 free-solid-svg-icons ,所以像 github 等图标我们无法使用,需要安装 free-brands-svg-icons 库才能使用。

具体说明参见fontawesome官方说明。

参考