Softwareentwicklung Zürich & Deutschschweiz

Register fontawesome icons for use with material MatIcon

29.04.2021
When implementing web applications there's always the same question. Which icon sets shall we use?
Since we use angular and material, it's obvious that we also use material icons. Nevertheless I recognized that for my requirements this icon set is not 'complete' one.
A good alternative is adding fontawesome or others (you can also add svgs and other fonts in the same way) and use the different sets side-by-side.

Add fontawesome to our angular project

First of all we need to include fontawesome in our angular app. There are two options how to do this.
1) Using npm package
You can install the npm package and register it in the styles section in angular.json
npm i font-awesome --save
"styles": [
    "node_modules/font-awesome/scss/font-awesome.scss",
]
2) Load from cdn
You can simply add a reference to the cdn in your index.html file.
<link rel="preload" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" as="style>

Register fontawesome to use with MatIcon

To make use of all icons the same way no matter which icon set our icon is included in, we need to register fontawesome (or your preferred font or svgs) with MatIconRegistry.
I usually use an own module for all material includes. So I will import and provide the icon references, here. You can also simply use the app.module for that.
import { MatIconModule, MatIconRegistry } from '@angular/material';

imports: [
	MatIconModule
 ],
 providers: [
	MatIconRegistry
 ]
	
Last but not least, you need to add fontawesome to the registry in your module.
export class MaterialModule {
	constructor(public matIconRegistry: MatIconRegistry) {
	  matIconRegistry.registerFontClassAlias('fontawesome', 'fa');
	}
}

Use fontawesome icons in HTML

Now you'll be able to use fontawesome in your mat-icon tags
<mat-icon fontSet="fa" fontIcon="fa-shopping-bag"></mat-icon>
You should adapt the size of the fontawesome icons to match the size of material icons. You can do this in the style.scss file as follows
.mat-icon.fa {
	font-size: 20px;
}  
If you have any questions or improvements please send me an email to
© 2016-2024 OneCodex GmbH – All rights reserved