MatSnackBar is an angular directive that’s used for showing a notification bar specifically on the mobile devices.
These types of UI components are generally used several times.
So to avoid the repetition of code, a service can simply be created to use SnackBar in different components.
Approach:
ng g s snackBar
import { Injectable } from '@angular/core'; import {MatSnackBar} from '@angular/material/snack-bar'; @Injectable({ providedIn: 'root'}) export class SnackBarService { //create an instance of MatSnackBar constructor(private snackBar:MatSnackBar) { } /* It takes three parameters 1.the message string 2.the action 3.the duration, alignment, etc. */ openSnackBar(message: string, action: string) { this.snackBar.open(message, action, { duration: 2000, }); } } |
chevron_right
filter_none
Now call the openSnackBar function wherever it is required, with the help of snackBService.
import { Component, OnInit } from '@angular/core'; import {SnackBarService} from '../snack.service'; @Component({ selector: 'app-profile', templateUrl: './snackBar.html', styleUrls: ['./snackBar.css'] }) export class SnackBar { // create an instance of SnackBarService constructor(private snackBService:SnackBarService) { } //defining method for display of SnackBar trigger(message:string, action:string) { this.snackBService.openSnackBar(message, action); } } |
chevron_right
filter_none
Example:
<button (click)="trigger('This is a ', 'SnackBar')"> SnackBarButton </button> |
chevron_right
filter_none
Output:

Recommended Posts:
- How to create a Snackbar using HMTL, CSS & JavaScript?
- Service Worker | How to create custom offline page ?
- Deploying Your Web App using Azure App Service
- Service Workers in Javascript
- $timeout service in AngularJS
- Why is Parse Server the future of Backend As A Service?
- Messaging Via Azure Service bus | SendMessage and ScheduleMessage
- Google Geo-coding Web Service (JSON response)
- How to create shapes using CSS ?
- How to create a copy of an object in PHP?
- How to create a skewed background using CSS ?
- How to Create Paradoxical Effect using CSS ?
- How to Create ToDo App using ReactJS ?
- How to Create Modules in Node.js ?
- Create a Tic-Tac-Toe Game using jQuery
- How to Create Border Animation using CSS ?
- How to Create a GrayScale Effect using CSS ?
- How to create a div element in jQuery ?
- How to create optional arguments in PHP ?
- How to create a PHP form that submit to self ?
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

