Here is my working example (Angular 11, Angular Material 11.0.1).
The most important part is to include MatSnackBarModule in the app.module.ts. Also, don't forget to import BrowserAnimationsModule as well.
import { MatSnackBarModule } from '@angular/material/snack-bar';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
@NgModule({
imports: [
MatSnackBarModule,
BrowserAnimationsModule
...
],
Then, my service looks like this
import { Injectable } from '@angular/core';
import { MatSnackBar } from '@angular/material/snack-bar';
@Injectable({
providedIn: 'root'
})
export class SnackbarService {
constructor(
private _snackBar: MatSnackBar) {
}
error(message: string) {
return this._snackBar.open(message, undefined, {panelClass: ['snackbar-error']});
}
success(message: string) {
return this._snackBar.open(message, undefined, {panelClass: ['snackbar-success']});
}
info(message: string) {
return this._snackBar.open(message, undefined, {panelClass: ['snackbar-info']});
}
}
To define styles, I added these to styles.scss
.mat-simple-snackbar {
font-size: 1.2em;
color: white;
}
.snackbar-error {
background-color: red;
}
.snackbar-success {
background-color: green;
}
.snackbar-info {
background-color: blue;
}
This way, I am now able to call SnackBar from anywhere in the code (including components from other modules). Usage example:
import { Component } from '@angular/core';
import { AuthService } from 'src/app/services/auth/auth.service';
import { SnackbarService } from 'src/app/services/snackbar.service';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss']
})
export class LoginComponent {
loginForm: any;
constructor(private authService: AuthService, private snackbar: SnackbarService) { }
onSubmit() {
this.authService.login(this.loginForm).subscribe(res => {
this.snackbar.success('Logged in');
}, e => {
this.snackbar.error('Login failed');
});
}
}