In Angular material, there is a nice built-in feature called Badge. Badges are like small status descriptors for any UI components.
It can be used in various places on the website like showing item count on the cart icon or showing notification count.
There are many uses of badges, which makes the website look nice.
In this tutorial, we will learn how to use Angular badge features on a website.
Please make sure to install Angular Material to see the Badge functionality in action.
Now let’s create a new project angular-material-badge using Angular CLI.
Create a New Angular Project
Open the command prompt or terminal of your computer and run the following command given below.
ng new angular-material-badge
The above code will generate a new project.
Now, navigate to the project folder and open it in the code editor by running the command given below.
Also, open the project in the browser using the command as shown below.
Now, we have a running project which you can see here http://localhost:4200/.
Install Angular Material and Import
As said above Angular Material is needed to implement the badge functionality. So try installing here if not installed yet.
After successful installation open app.module.ts file and import MatBadgeModule.
Open the app.component.html file in the code editor by navigating the src/app and replace it with the below code.
<div> <h1>Angular Material Badge</h1> <p> <span matBadge="4" matBadgeOverlap="false">Text with a badge</span> </p> <p> <span matBadge="1" matBadgeSize="large">Text with large badge</span> </p> </div>
now refresh the browser and you will see like this.
Angular Material Badge Position
By default, the badge position is placed above after. But you can easily change the direction of the badge by just changing the attribute matBadgePosition.
See the code below
<button mat-raised-button color="accent" matBadge="99" matBadgePosition="before" matBadgeColor="primary"> Action </button>
Angular Material Badge Size
By default, the badge is set to size medium. You can change the badge size by changing the attribute matBadgeSize to small, medium, or large whichever you want.
see the code snippet below:
<span matBadge="4" matBadgeSize="small">Badge text in small size</span>
Set Badge visibility
The badge visibility can be set by toggling the value true and false to matBadgeHidden.
see the code snippets shown below:
<button mat-raised-button matBadge="9" [matBadgeHidden]="true" (click)="toggleBadgeVisibility()"> Show </button>
You can get detailed information about the badge here.
If you want to integrate badge functionality in any Angular version, this tutorial will work fine.
Finally. The Badge tutorial is over. Feel free to ask any question in the comment section below