Angular Material library has a wide variety of components that we can use. One such component is <mat-icon>. The <mat-icon> directive supports icon fonts and SVG icons but not bitmap-based formats (png, jpg, etc.).
Here is the step-by-step guide to implementing Material Icons in Angular:
Step 1: Setup Angular 18 Project
If you have not installed Angular CLI, you can install it using the below command:
npm install -g @angular/cli
Now, you can create a new Angular project using the below command:
ng new icon-app
Go inside the project folder:
cd icon-app
Step 2: Install Angular material
Add the angular material library to your Angular project using the below command:
ng add @angular/material
Step 3: Import Material Icons
To use material icons inside the Angular app, import the icon module in your src/app/app.component.ts file:
import { Component } from '@angular/core'; import { RouterOutlet } from '@angular/router'; import { MatIconModule } from '@angular/material/icon'; @Component({ selector: 'app-root', standalone: true, imports: [RouterOutlet, MatIconModule], templateUrl: './app.component.html', styleUrl: './app.component.css', }) export class AppComponent { title = 'icon-app'; }
In this code, we imported MatIconModule from the Angular material icon library.
Step 4: Include Material Icons Font
The next step is to include the Material Icons font in our index.html file.
Add the following line inside the <head> tag:
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
Step 5: Using Material Icons in Components
After importing and configuring material icons, now you can use the icons in your component.
Open the src/app/app.component.html file and add a Material icon like this:
<div class="icon-container"> <mat-icon>home</mat-icon> <mat-icon class="material-icons-outlined">favorite</mat-icon> <mat-icon class="material-icons-round">settings</mat-icon> <mat-icon class="material-icons-two-tone">alarm</mat-icon> <mat-icon class="material-icons-sharp">face</mat-icon> </div>
To style these icons, add the below code in the src/app/app.component.css file:
.icon-container { display: flex; justify-content: space-around; align-items: center; margin: 20px; } mat-icon { font-size: 100; color: #3f51b5; }
Step 6: Running the Application
Go to the terminal and start the development server using this command:
ng serve --open
It will open up the browser with this URL: http://localhost:4200/
That’s all!
Ajay Chandan
What if I wanna change the URL conditionally. I don’t get an example of that
Case: in the constructor, I have registered with a URL and on every click, I would like to change it.