Angular Material SnackBar

Table of Contents
Overview
In this example the application will open a Snackbar with different colors for success or error. This example assumes that Angular Material has already been installed with the following.
ng add @angular/material
From your component.ts file, import the SnackBar and your own service;
import { MatSnackBar, MAT_SNACK_BAR_DATA, MatSnackBarRef } from '@angular/material/snack-bar';
import { YourService } from 'src/app/services/your.service';
Add it to the constructor
constructor(private snackBar: MatSnackBar,
private YOURSERVICE: YourService ) { }
Function to open the snackbar.
Note the position is to appear at the top versus the default (bottom).
openSnackBar(message: string, action: string, toolbarColor: string) {
this.snackBar.open(message, action, {
duration: 2000,
verticalPosition: 'top',
panelClass: ['mat-toolbar', toolbarColor]
});
}
The service call success or error.
this.obsSubscription = this.YOURSERVICE.addRecord(this.dataForm).subscribe((data) => {
if (data.status === 409) {
this.openSnackBar(data.msg, 'Close', 'mat-warn');
} else {
this.openSnackBar(data.msg, 'Close', 'mat-primary');
}
},
(err: HttpErrorResponse) => {
console.log(err);
});
}
There are three different options for color. mat-primary, mat-warn, and mat-accent.


You must be logged in to post a comment.