Snackbar Material Service

June 2, 2021 · 1 min readLucian Ciobanu
Tags:Angular

Material Snackbar is a very cool and modern way of delivering alerts to the user. What I found even more useful is to have it included in a service so the code can be reused.

snackbar.service.ts

import { Injectable } from '@angular/core';
import { MatSnackBar } from '@angular/material/snack-bar;

@Injectable({
  providedIn: 'root'
})
export class SnackbarService {
  constructor(priavate snackSErvice: MatSnackBar) {}
  
  public showServerError() {
    this.snackService.open('Server error, please try again.', 'OK');
  }
  
  public openCustomMessage(message: string, buttonLabel: string, autoclose?: boolean) {
    this.snackService.open(message, buttonLabel, { duration: autoclose ? 5000 : undefined});
  }
  
  public dismissSnackBar() {
    this.snackService.dismiss();
  }
}

Also included a cool autoclose optional parameter for those message I want to show for only 5 seconds.

Another little something that could be included in the object with options to provide a nicer UI/UX is the panelClass property which can be whatever string but 'success' and/or 'error' are great candidates if you would like to style the notifications separatelly.

All that's left now is to have the service imported in the components you'd like to use it and call these awesome properties.

Hope this helped!

Cheers,
Lucian

Picture of author

Web Development & Software Delivery