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 ?
- Why is Parse Server the future of Backend As A Service?
- Google Geo-coding Web Service (JSON response)
- Service Workers in Javascript
- $timeout service in AngularJS
- Deploying Your Web App using Azure App Service
- Messaging Via Azure Service bus | SendMessage and ScheduleMessage
- How to watch service variables ?
- Create a Website Alarm Using Python
- How to create a responsive Modal Sign-Up form for a Website?
- How to create an HTML button that acts like a link?
- How to create optional arguments for a SASS mixin?
- How to create Glowing Star effect using HTML and CSS?
- Create a web server and run PHP script on it using Raspberry Pi
- Create an unordered list without any bullets using CSS
- How to create slide left and right toggle effect using jQuery?
- How to create auto-resize textarea using JavaScript/jQuery ?
- How to create directory with HTML button and PHP ?
- How to create comma separated list from an array in PHP ?
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.

