In this example we will register svg icon in our Angular application (Angular 8 in our case) and use it inside of mat-icon element as a regular icon. We will show two different ways, by loading the svg file addSvgIcon() and by using literal svg source addSvgIconLiteral().
Let's assume you already have angular material installed in your application.
First we have to find our icon on https://materialdesignicons.com/ like for example this one: book-open-page-variant. Download the icon to your application folder, for example src/assets/icons/book-open-page-variant.svg
Next, open app.components.ts and include MatIconRegistry and DomSanitizer
import { MatIconRegistry } from '@angular/material/icon';
import {DomSanitizer} from '@angular/platform-browser';
constructor(
private matIconRegistry:MatIconRegistry,
private domSanitzer:DomSanitizer,
){}
Now when we included Material Icon Registry we can actually register our icon to be used anywhere inside of our application. In this tutorial we will show two different examples: using svg file, and using svg code
1. Import SVG as a file to your Angular Material app
In our app.components.ts inside of constructor we will simply call MatIconRegistry give our icon a name and path where the file is located:
constructor(
private matIconRegistry:MatIconRegistry,
private domSanitzer:DomSanitizer,
){
this.matIconRegistry.addSvgIcon(
'open_book',
this.domSanitzer.bypassSecurityTrustResourceUrl('assets/icons/book-open-page-variant.svg')
);
}
2. Import SVG as a inline code to your Angular Material app
constructor(
private matIconRegistry:MatIconRegistry,
private domSanitzer:DomSanitizer,
){
this.matIconRegistry.addSvgIconLiteral(
'open_book',
this.domSanitzer.bypassSecurityTrustHtml('<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="24" height="24" viewBox="0 0 24 24"><path d="M19,2L14,6.5V17.5L19,13V2M6.5,5C4.55,5 2.45,5.4 1,6.5V21.16C1,21.41 1.25,21.66 1.5,21.66C1.6,21.66 1.65,21.59 1.75,21.59C3.1,20.94 5.05,20.5 6.5,20.5C8.45,20.5 10.55,20.9 12,22C13.35,21.15 15.8,20.5 17.5,20.5C19.15,20.5 20.85,20.81 22.25,21.56C22.35,21.61 22.4,21.59 22.5,21.59C22.75,21.59 23,21.34 23,21.09V6.5C22.4,6.05 21.75,5.75 21,5.5V7.5L21,13V19C19.9,18.65 18.7,18.5 17.5,18.5C15.8,18.5 13.35,19.15 12,20V13L12,8.5V6.5C10.55,5.4 8.45,5 6.5,5V5Z" /></svg>')
);
}
After you have implemented one of these options, we can now simply use our icon inside of any component like this
<mat-icon svgIcon="open_book"></mat-icon>