How To Create Error and Success Messages Easily with Angular Material
Jacob Naryan - Full-Stack Developer
Posted: Sat Jul 22 2023
Last updated: Wed Nov 22 2023
If you are prototyping a web app and want a clean UI component for sharing success and error messages with your user, then Angular Material’s Snack Bar module is for you. In this tutorial, I will show you how to use it.
1. Install Angular Material
Before you can use Angular Material’s Snackbar module in your Angular project, you must first install the package. To do this, run the following command in your terminal:
ng add @angular/material
2. Import Snackbar Module
Once you have installed the package, you can then import the Snackbar module into your component. To do this, add the following line of code to the top of your component file:
import {MatSnackBar} from '@angular/material/snack-bar';
Inject the snack bar module into your component by adding it to the constructor.
constructor(private _snackBar: MatSnackBar){
}
3. Create a Method to Open the Snackbar
Next, create a method in your component that will open the snack bar. To do this, add the following method to your component:
openSnackBar(message: string, type: string) {
this._snackBar.open('There was an error', 'X')
}
This method takes two parameters — a message and an action. When the method is called, it will open a snack bar with the specified message. A close button will be displayed with the text you supplied for the action.
You can also provide an object as a third optional parameter which allows you to configure the snack bar further. For example, you can show the snack bar for a set duration like:
this._snackBar.open('There was an error', 'X', {
duration: 3000
});
This shows the snack bar for a duration of 3 seconds.
4. Call the Method
The final step is to call the method when needed, for example when an error or success occurs. To do this, add the following line of code wherever needed:
this.openSnackBar('Your message', 'X');
This will generate a snack bar message that looks like:
Thank you for reading. If you liked this blog check out more tutorials about software engineering here.