Use Font Awesome icons across the application in Angular8

Viewed 422

I'm working on a quite big angular application with lazy loading modules implemented. In a lot of components, in differents modules, I use icons from font Awesome. Actually, icon are implemented individually like in this example:

In component.ts:

import { faChevronDown, faChevronUp, faTimes } from '@fortawesome/free-solid-svg-icons';

public faChevronDown= faChevronDown;

public faChevronDown= faChevronUp;

in component.html:

<fa-icon class="fa-md" [icon]="faChevronDown"></fa-icon>

Since I'm starting to have a lot of icons, that sometimes are the same in differents components, I was wondering if there is a way to factorise this code. For example, instead of declaring a property for each icon in each component, some kind of global item where I can stock all icons I want to use and call them directly in HTML when needed.

Following this article of the Angular Wiki, I find out the library.add() method that seemed to be perfect for this purpose, so I tried to implement it:

In app.module:


import { faChevronDown, faChevronUp} from '@fortawesome/free-solid-svg-icons';

@NgModule({

  declarations: [

    AppComponent

  ],

  imports: [

    BrowserModule,

    FontAwesomeModule

  ],

  providers: [],

  bootstrap: [AppComponent]

})

export class AppModule {

  constructor() {

    library.add(faChevronDown, faChevronUp);

  }

}

and in my component.html:

<fa-icon class="fa-md" icon="faChevronDown"></fa-icon>

But I still have errors: in my display I don't see any Icon (the screen is displaying but where I should see Icons it's empty), and in console I have this error:

FontAwesome: Property icon is required for fa-icon/fa-duotone-icon components. This warning will become a hard error in 0.6.0.

So I need to fix it or to find another proper solution to factorise icons in my application.

2 Answers

The problem is probably because you did not explicity declare faChevronDown in the component where you are using it.

You have to have something like

import { faChevronDown, faChevronUp} from '@fortawesome/free-solid-svg-icons';

export class YourComponent {
 faChevronDown = faChevronDown;
 ...
}

Then in your HTML template

 <fa-icon [icon]="faChevronDown"></fa-icon>

Are you declaring the component, that uses the Font Awesome icon in its template, in the same module that imports the FontAwesomeModule?

Sticking to your example, your template should then look like the following:

<fa-icon class="fa-md" icon="chevron-down"></fa-icon>

You can find the appropriate icon names that you need to use, by finding the icon over on the website of Font Awesome itself.

Related