Implementing a re-usable Angular Material Snackbar service

 

Implementing a generic Angular Material Snackbar service

When developing web applications, it is common to display feedback messages to users. A snackbar is a popular way of conveying short-lived messages to a user. A snackbar is a dismissible message that appears temporarily at a fixed position on the screen.

In this blog, we will discuss how to create a generic and re-usable angular material snackbar implementation within an angular service

Creating the Snackbar Service

To create the Snackbar service, we need to first generate a new service using the Angular CLI. We can do this by running the following command in the terminal:

ng generate service snackbar

This will generate a new service file named snackbar.service.ts in the src/app directory.

Next, we need to import the MatSnackBar module from Angular Material. We can do this by adding the following line at the top of the snackbar.service.ts file:

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

We can then inject the MatSnackBar module in the constructor of the SnackbarService class:

constructor(private snackBar: MatSnackBar) { }

Creating the Snackbar Configuration

With the SnackbarService in place, we can now proceed to define the snackbar configuration. This configuration will enable us to display snackbars of various types, each with its own unique style that is appropriate for the type of message we are trying to convey.

Typically , there are four main message types:

  • success : which conveys that an action / event has succeeded
  • warning : which is useful for highlighting non-breaking undesirable behaviors
  • error: which is useful for conveying events / actions that can cause of have caused the application to throw an error or exception
  • default : which is useful for conveying information type messages to the user

export enum SNACK_BAR_MESSAGE_TYPE {
  success = 'green-success-snackbar',
  warning = 'orange-warning-snackbar',
  error = 'red-error-snackbar',
  default = 'default-snackbar'
}

The code block above defines an enum for SNACK_BAR_MESSAGE_TYPE that maps different message types to different CSS classes. In order for this configuration to work , we need to also ensure we create the CSS classes

.green-success-snackbar {
  background-color: #2bbe68 !important; ;
  color: #fff ;
  font-weight: 500;
}

.red-error-snackbar {
  background-color: #ff3737 !important;
  color: #fff ;
  font-weight: 500;
}

.orange-warning-snackbar {
  background-color:  #ff6f00 !important;
  color: #fff ;
  font-weight: 500;
}

.default-snackbar{
  font-weight: 500;
}

Implementing the Snackbar Logic

Now that we've created our configuration and defined our message types , we can proceed with implementing the logic for displaying the snackbar.

This involves defining a showSnackBar function that takes in a context and message parameter, and uses the MatSnackBar module to display a snackbar with the specified message, duration, and CSS class.

public showSnackBar(context: string, message: string) {
    this.matSnackBar.open(message, '', {
      duration: 3000,
      panelClass: [context || SNACK_BAR_MESSAGE_TYPE.default],
      verticalPosition: 'top',
      horizontalPosition: 'center'
    });
  }

  public showErrorMessage(message: string) {
    this.showSnackBar(SNACK_BAR_MESSAGE_TYPE.error, message);
  }

  public showSuccessMessage(message: string) {
    this.showSnackBar(SNACK_BAR_MESSAGE_TYPE.success, message);
  }

  public showWarningMessage(message: string) {
    this.showSnackBar(SNACK_BAR_MESSAGE_TYPE.warning, message);
  }

  public showDefaultMessage(message: string) {
    this.showSnackBar(SNACK_BAR_MESSAGE_TYPE.default, message);
  }

  public showServiceFailureMessage(serviceName: string, error: ErrorEvent) {
    const errorMessage = error.message ? error.message : error.error.message;
    const errorLabel = `${serviceName} service has failed: ${errorMessage}`;
    this.showErrorMessage(errorLabel);
  }

We also defined several helper functions that call showSnackBar with different context parameters, such as showErrorMessage, showSuccessMessage, showWarningMessage, and showDefaultMessage which allows us to easily display our notification in the style thats appropriate , by passing just a message as a parameter.

Additionally, we created a showServiceFailureMessage function that takes in a serviceName and error parameter, and constructs an error message to display in the snackbar. Showing how we can enhance and extend our snackbar functionality.

Using the Snackbar Service

We can now use the SnackbarService to display a snackbar in any component in our Angular application. To do this, we need to first import the SnackbarService module:

import { SnackbarService } from './snackbar.service';

We can then inject the SnackbarService in the constructor of the component where we want to display the snackbar:

constructor(private snackbarService: SnackbarService) { }

Finally, we can call the showSuccessMessage function and pass in the message we would like to display

this.snackbarService.showSuccessMessage('Hello, World!');

This will display a success snackbar at the top of the screen with the message "Hello, World!"

Conclusion

By creating a SnackbarService, we can easily display feedback messages to users in any component in our Angular application. With this implementation, we can keep our code DRY and make it easier to maintain.

Comments