Angular 2/4 How to style angular material design snackbar
I made the following code to work with Angular 6 and Angular Material 6.
The service that contain the snackBar calls:
@Injectable()
export class MessageService {
constructor(private snackBar: MatSnackBar) {}
showError(message: string) {
const config = new MatSnackBarConfig();
config.panelClass = ['background-red'];
config.duration = 5000;
this.snackBar.open(message, null, config);
}
}
Add the css class in the styles.css file:
.background-red{
background-color: rgb(153, 50, 50);
}
md-snackbar
provides a service to provide custom config
. One the properties of config
is extraClasses
that allows to add CSS classes to the snack bar container (doc).
extraClasses
can be used with ::ng-deep
to override the default CSS classes. Here's an example:
component.ts:
Requires following import
in the component:
import {MdSnackBar, MdSnackBarConfig} from '@angular/material';
(providing custom configuration)
openSnackBar(message: string, action?: string) {
let config = new MdSnackBarConfig();
config.extraClasses = ['custom-class'];
this.snackBar.open(message, action ? 'Action Label' : undefined, config);
}
component.css:
::ng-deep snack-bar-container.custom-class {
background: yellow;
}
::ng-deep .custom-class .mat-simple-snackbar {
color: green;
}
Here's a Plunker demo if you would like to try.
NOV 2018 UPDATE: Angular 6+
The syntax has changed a bit, with the md-
prefix being replaced mat-
and extraClasses
was replaced with panelClass
. The function is overall the same though:
const config = new MatSnackBarConfig();
config.panelClass = ['custom-class'];
...
and the imports too:
import { MatSnackBar, MatSnackBarConfig } from '@angular/material';