Twitter LogoFacebook Logo
Angular Material UI: Badges
Hello, in this tutorial, I will be talking badges from Angular Material.
By: King Wai Mark

To add a badge to an element, just apply the mat-badge attribute to it and give it a string or numeric value that you want to display. This will place the badge on the right side of the element. 

<element mat-badge="5"></element>

Image from Codeible.com

Implementation

To begin, add the MatBadgeModule to your project. Go to the app module TypeScript file, add the import statement, and add it to the app.

...
import MatBadgeModule from '@angular/material/badge';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    ...
    MatBadgeModule,
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Add Badges

To add an badge to a button, we would apply the matBadge attribute to it and set its value.

<button matBadge="1">Badge Example</button>

However, instead of using a static value, we can bring in a variable from the Typescript File. This allows us to programmatically change the value.

TypeScript

var myVariable = "2";

HTML

<button matBadge="{{myVariable}}">Badge Example</button>

Changing the badge

To place the badge on the left side, apply the matBadgePosition attribute and set the value to before.

<button 

   matBadge="{{myVariable}}"
   matBadgePosition="before"
>Badge Example</button>

Moreover, we can change the size, visibility, and color. 


The badge has 3 sizes – small, medium, and large. To change the size, apply the matBadgeSize attribute and set it to small, medium, or larger.

matBadgeSize="small | medium | large"

If we want a smaller badge, we would put small or if we want a larger badge, we will put large. Medium is the default size.

<button 

   matBadge="{{myVariable}}"
   matBadgePosition="before"
   matBadgeSize="small"
>Badge Example</button>

Sometimes we may want to hide the badge. To hide the badge, use the [matBadgeHidden] attribute and set it to true if we want to hide it or false if we want to show it. 

<button 

   matBadge="{{myVariable}}"
   matBadgePosition="before"
   matBadgeSize="small"
   [matBadgeHidden]="true"
>Badge Example</button>

Lastly, to change the color, apply the matBadgeColor attribute and set it to either primary, accent, or warn


These 3 color themes are predefined depending on the theme you have chosen when you added Angular Material to your project. 

matBadgeColor="primary| accent| warn"

<button 

   matBadge="{{myVariable}}"
   matBadgePosition="before"
   matBadgeSize="small"
   [matBadgeHidden]="true"
   [matBadgeColor]=" 'primary' "
>Badge Example</button>


Sign In