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,
});
}
} |
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);
}
} |
Example:
< button (click)="trigger('This is a ', 'SnackBar')">
SnackBarButton
</ button >
|
Output: