3

Baseline:

  • Angular 6.0.3
  • Angular Materials 6.4.2
  • "@fortawesome/angular-fontawesome": "^0.1.1"
  • "@fortawesome/fontawesome-svg-core": "^1.2.2"
  • "@fortawesome/free-solid-svg-icons": "^5.2.0"

    So I have installed angular-fontawesome and I'm trying to get the <mat-icon> directive to work, but its not. I was unclear on how to register the fonts or if I even needed too. I'm looking for an example of where someone is using the new font-awesome with angular and what is needed to use the <mat-icon> directive to get the icons to display. If I follow the instructions on the angular-font-awesome GitHub page it all works, but they are using tags like this: <fa-icon icon="coffee"></fa-icon>

Can someone please go through the setup so I can get these to render using the <mat-icon> directive.

SRSonnenwald
  • 181
  • 2
  • 11

1 Answers1

2

Taken straight from this link, implemented and working into my project, these are the steps I followed.

  1. Install relevant FontAwesome libraries

    npm i @fortawesome/fontawesome-svg-core
    npm i @fortawesome/free-brands-svg-icons
    npm i @fortawesome/free-regular-svg-icons
    npm i @fortawesome/free-solid-svg-icons
    
  2. Create icon service

    import { Injectable } from '@angular/core';
    import { MatIconRegistry } from '@angular/material';
    import { DomSanitizer } from '@angular/platform-browser';
    import { IconDefinition } from '@fortawesome/fontawesome-svg-core';
    
    @Injectable({
      providedIn: 'root'
    })
    export class IconService {
      constructor(private _iconRegistry: MatIconRegistry, private _sanitizer: DomSanitizer) {}
      addSvg(icon: IconDefinition) {
        const svg = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${icon.icon[0]} ${icon.icon[1]}">
            <path d="${icon.icon[4]}" />
          </svg>`;
    
        this._iconRegistry.getNamedSvgIcon(icon.iconName, icon.prefix).subscribe(
          () => {
            //Ok, icon already exists
          },
          () => {
            //Error, not found, add it
            this._iconRegistry.addSvgIconLiteralInNamespace(
              icon.prefix,
              icon.iconName,
              this._sanitizer.bypassSecurityTrustHtml(svg)
            );
          }
        );
      }
    }
    
  3. Add the icons you require, this should be done on an as-needs basis to prevent bundle bloat

    // In app.component or relevant component requiring icon
    import { faGoogle } from '@fortawesome/free-brands-svg-icons';
    /*...*/
    constructor(
      _iconService: IconService
    ) {
      _iconService.addSvg(faGoogle); // add icon to library
    }
    
  4. Use your icon

    <mat-icon svgIcon="fab:google"></mat-icon>
    
FernAndr
  • 1,448
  • 1
  • 14
  • 26
John B
  • 1,129
  • 14
  • 23