Search code examples
angular-material2angular-fontawesome

How do I use angular-fontawesome with Angular Material?


Existing questions on this subject refer to how to use Angular with FontAwesome Icons and the Answer is ideally Angular FontAwesome. I searched both repo's and didn't really find much using angular-fontawesome. There are hints of older solutions only.

So I have that. I am also using Angular Material Buttons, to which I have been tasked with using FontAwesome Icons in my Buttons and this leads me to Material Icons

I am not really sure where to begin.

Providing I have added an Icon to angular-fontawesome as described. I have a Button with a Icon ready to go, there is a standard method to use to connect the two?

TLDR: I want to use a Material Icon Button, but I am unable to use a Material Icon and have to use FontAwesome Icons instead. I don't know how to achieve this.


Solution

  • Approach 1: Material icon registry

    Material allows to use custom SVG icons with its components (like mat-button). FontAwesome icons are also SVGs, so you can use this mechanism to solve task at hand.

    // 1. Import desired FontAwesome icon
    import { faFontAwesomeFlag } from '@fortawesome/free-brands-svg-icons';
    import { icon } from '@fortawesome/fontawesome-svg-core';
    
    // 4. Use with `mat-icon` component in your template
    @Component({ template: '<button mat-button type="button"><mat-icon svgIcon="font-awesome" style="vertical-align: top"></mat-icon>Make Awesome!</button>' })
    export class AppComponent {
      constructor(registry: MatIconRegistry, sanitizer: DomSanitizer) {
        // 2. Render icon into SVG string
        const svg = icon(faFontAwesomeFlag).html.join('');
        // 3. Register custom SVG icon in `MatIconRegistry`
        registry.addSvgIconLiteral(
          'font-awesome', 
          sanitizer.bypassSecurityTrustHtml(svg)
        );
      }
    }
    

    Also check this issue for description of a more lightweight implementation.

    Approach 2: Use fa-icon component from angular-fontawesome library

    As you already seem to use @fortawesome/angular-fontawesome package in your application, you can avoid using mat-icon altogether and use fa-icon inside mat-button instead.

    import { faFontAwesomeFlag } from '@fortawesome/free-brands-svg-icons';
    
    @Component({ template: '<button mat-button type="button"><fa-icon [icon]="faFontAwesomeFlag" style="padding-right: 6px"></fa-icon>Make Awesome!</button>' })
    export class AppComponent {
      faFontAwesomeFlag = faFontAwesomeFlag;
    }
    
    

    Note that you'll also need to add FontAwesomeModule to imports for this to work. See documentation for more details.


    Here is the demo with both described approaches: https://stackblitz.com/edit/components-issue-8znrc5

    Note that I also had to add some CSS to ensure that icon is aligned well with the button text.