How to add a loading spinner to an Angular Material button (Step-by-step Guide)

Daniel Kreider
Daniel Kreider
Published on October 24th at 7:00am
  • Angular
  • Angular Material
  • Angular Spinner Example

Say, wouldn't it be dandy if the Angular Material button had a loading spinner option?

Well here's the 2-minute guide that will teach you how to add a loading spinner to the Angular Material Button

Err…

…wouldn't it be nice if Angular Material had a button with a loading spinner?

Like maybe a CSS class or attribute that we could toggle to put our Angular material button into a loading state?

Instead of ranting I decided to try to build my own solution  -  and succeeded!

With no further ado, here's how to add a spinner to an Angular Material button.

Our CSS File

@keyframes spinner {
  to {transform: rotate(360deg);}
}

.spinner:before {
  content: '';
  box-sizing: border-box;
  position: absolute;
  top: 50%;
  left: 50%;
  width: 20px;
  height: 20px;
  margin-top: -10px;
  margin-left: -10px;
  border-radius: 50%;
  border: 2px solid #ffffff;
  border-top-color: #000000;
  animation: spinner .8s linear infinite;
}

Our HTML File

<div style="text-align:center">
  <button mat-raised-button color="primary" [class.spinner]="loading" [disabled]="loading" (click)="save()">Save</button>
</div>

Our .ts file (the logic)

export class AppComponent{
  title = 'hello-world';
  loading = false;

  save(): void {
    this.loading = true;
    // do your saving thing here
  }
}

Done!

I told you this was simple. You're welcome. Hope you enjoyed it!

Questions or comments? Don't hesitate to contact me.

Angular Consultant