Tutorial

How To Use Custom SVG Icons in Angular Material

Updated on January 26, 2021
author

WeiHung Chin

How To Use Custom SVG Icons in Angular Material

Introduction

The Angular Material library offers a suite of Angular components styled with Material Design. One such component is the <mat-icon> component. There are a wide range of ready-made Material icons. But what if we want to display some custom icons while staying consistent with the Material Design styling? Let’s learn how to use our own SVG icons in Angular Material components.

In this tutorial, you will use the <mat-icon> component to use the standard Material Icons font. Then, you will use the <mat-icon> component to support a custom SVG icon.

The full working code can be found on this GitHub repo.

Prerequisites

To complete this tutorial, you will need:

This post assumes you have some basic knowledge of Angular v4.2+.

This tutorial was originally written with Angular v5.2+ and Angular Material v5.2.4.

This tutorial was verified with Angular v10.0.5 and Angular Material v10.1.1.

You can refer to this post if you’re getting started with Angular Material.

Step 1 — Creating an Angular Project and Installing Dependencies

First, open your terminal and create a new project directory:

  1. mkdir angular-material-custom-svg

Next, navigate to the new directory:

  1. cd angular-material-custom-svg

Then, use npm to install Angular CLI as a devDependency:

  1. npm install @angular/cli@10.0.4 --save-dev

Now, you can use Angular CLI to create a new Angular project and also set some options for the needs of this tutorial:

  1. ng new angular-material-custom-svg --directory=. --skipTests=true --routing=false --style=css

This gives you a fresh Angular project in the current directory. Let’s install Angular Material and its dependencies with the following command:

  1. npm install @angular/material@10.1.1 @angular/cdk@10.1.1 --save

That concludes setting up the tutorial project. We can now continue on to using Material icons in our project.

Step 2 — Using <mat-icon> with Icon Fonts

In order to use the default Material Icons, you’ll need to first import them in the global stylesheet. To do this, open the styles.css file (that was generated by Angular CLI):

  1. nano src/styles.css

Replace the contents of the file with the following import statement:

src/style.css
@import url("https://fonts.googleapis.com/icon?family=Material+Icons");

Next, you will need to import MatIconModule. Open the app.module.ts file:

  1. nano src/app.module.ts

Then, add the import for MatIconModule:

src/app/app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { MatIconModule } from "@angular/material/icon";

And add it to the module’s array of imports:

src/app/app.module.ts
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    MatIconModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})

Now, you can use the built-in material icons with the <mat-icon> component. If you add the textual name for an icon, it will display the associated icon glyph.

For our tutorial, we will be adding the "mood" icon (this resembles the symbol of a face with a smile):

The Material Icon glyph for mood

The Material Design website has a full list of Material icons which you can use directly.

Open the app.component.html file:

  1. nano src/app/app.component.html

Replace the contents of the file with the following line of code:

src/app/app.component.html
<mat-icon>mood</mat-icon>

Let’s take a look at what we have so far! Start the application:

  1. ng serve

View the application in your web browser (localhost:4200), and you will see the "mood" icon.

That concludes using <mat-icon> to display icon fonts. We can continue on to using <mat-icon> to display SVGs.

Step 3 — Using <mat-icon> with SVGs

Let’s add a custom "unicorn" icon to our project.

Note: It is possible to acquire unicorn SVG icons at The Noun Project. Free basic usage must attribute the creator of the icon per license requirements.

Save the icon as unicorn_icon.svg to the src/assets folder of your project.

To use our custom unicorn icon with the <mat-icon> component tag, we’ll need to import HttpClientModule.

Open the app.module.ts file:

  1. nano src/app/app.module.ts

Then, add the import for HttpClientModule:

src/app/app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { MatIconModule } from "@angular/material/icon";
import { HttpClientModule } from "@angular/common/http";

And add it to the module’s array of imports:

src/app/app.module.ts
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    MatIconModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})

Now, we can register our custom "unicorn" icon with the MatIconRegistry service provided by Angular Material.

Open app.component.ts:

  1. nano src/app/app.component.ts

Then, add the import for MatIconRegistry:

src/app/app.component.ts
import { Component } from "@angular/core";
import { MatIconRegistry } from "@angular/material/icon";

And add the injection of the service into the component:

src/app/app.component.ts
export class AppComponent{
  constructor(private matIconRegistry: MatIconRegistry){
    // ...
  }
}

Add the addSvgIcon method to the component’s constructor method:

src/app/app.component.ts
export class AppComponent{
  constructor(private matIconRegistry: MatIconRegistry){
    this.matIconRegistry.addSvgIcon(
      `icon_label`,
      `path_to_custom_icon.svg`
    );
  }
}

The addSvgIcon method registers our icon by taking in two arguments.

The first argument is the icon label, which is of type string.

The second argument is the relative URL path pointing to the location of the icon file.

This URL path string is of type SafeResourceUrl. To parse the URL path string into SafeResourceUrl, we can make use of the DomSanitizer provided by Angular.

Next, add the import for DomSanitizer:

src/app/app.component.ts
import { Component } from "@angular/core";
import { MatIconRegistry } from "@angular/material/icon";
import { DomSanitizer } from "@angular/platform-browser";

And add the injection of the service into the component:

src/app/app.component.ts
export class AppComponent{
  constructor(
    private matIconRegistry: MatIconRegistry,
    private domSanitizer: DomSanitizer
  ){
    this.matIconRegistry.addSvgIcon(
      `icon_label`,
      `path_to_custom_icon.svg`
    );
  }
}

Given a relative URL path string, the bypassSecurityTrustResourceUrl method on DomSanitizer will return a safe resource URL, which is required by the addSvgIcon method.

Now, you can replaceicon_label with the custom "unicorn" label. And path_to_custom_icon.svg with the custom "unicorn_icon.svg" icon.

Let’s update the lines in addSvgIcon:

src/app/app.component.ts
export class AppComponent{
  constructor(
    private matIconRegistry: MatIconRegistry,
    private domSanitizer: DomSanitizer
  ){
    this.matIconRegistry.addSvgIcon(
      "unicorn",
      this.domSanitizer.bypassSecurityTrustResourceUrl("../assets/unicorn_icon.svg")
    );
  }
}

Now, the custom "unicorn" icon is properly registered with the MatIconRegistry service.

To display the custom icon, you will need to update the component’s template. Open app.component.html:

  1. nano src/app/app.component.html

And pass the icon label to the svgIcon input property of <mat-icon>:

src/app/app.component.html
<mat-icon svgIcon="unicorn"></mat-icon>

Let’s take a look at what you have so far! Start the application:

  1. ng serve

View the application in your web browser (localhost:4200), and you will see that the custom icon is displayed with Material styling.

Now, you’re able to display a full set of custom icons in your apps with Material styling.

To make the code cleaner and more maintainable, we can refactor the code by moving the MatIconRegistry into a service class.

Conclusion

In this tutorial, you have completed an initial exploration into using Angular Material’s <mat-icon> component with the Material Icons font and custom SVGs. This provides a way to maintain consistent adherence to Material Design styling throughout your application.

If you’d like to learn more about Angular, check out our Angular topic page for exercises and programming projects.

If you’d like to learn more about Material Design, check out the official documentation.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
WeiHung Chin

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
3 Comments


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

can we change the color of the svg icon using properties ?

Great tutorial, thank you!

<mat-icon svgIcon="example"></mat-icon> works perfect.

But I’m struggling using custom SVG icons within a mat-list as mat-list-item. I m able to register the icon in MatIconRegistry but nothing will be displayed when using it, like <mat-icon svgIcon="example">.

Is there a way to use custom SVG icons in mat-list like the regular icons as follows:

<mat-list>
  <mat-list-item (click)="navToHome()" class="mat-list-option">
    <mat-icon mat-list-icon>home</mat-icon>
    <h4 mat-line>{{'lbl.home' | translate}}</h4>
  </mat-list-item>
</mat-list>

Hi, Thank you for this article. I used the same approach but i got into a problem. I am using path as ../../../assets/svgicons/save.svg Now it is working in dev mode but when i build my project and run it on server then error is coming that save.svg count not found. Can you please help how can i give path for my svg may be i am doing something wrong.

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Become a contributor for community

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

DigitalOcean Documentation

Full documentation for every DigitalOcean product.

Resources for startups and SMBs

The Wave has everything you need to know about building a business, from raising funding to marketing your product.

Get our newsletter

Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

New accounts only. By submitting your email you agree to our Privacy Policy

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.