Customize the background color of the Angular Material Snackbar (Guide)
Angular Material is a popular UI library for building Angular apps.
But sometimes we might want to style the Angular Material components to match our design guidelines or style.
For example, we might want to style the Angular Input component to look different then the standard option.
Or we might want to customize the style of the Angular Material table.
Today we're going to learn how to customize the background color of the Angular Material Snackbar component.
It's actually quite easy once you understand how to do it.
Using the Angular Material root variables
One of the basic concepts we need to understand when styling the Angular Material snackbar component is that we can use CSS variables to help set the background styles.
This is done using the root CSS option.
For example, if we wanted to set the background color of the Angular Material table we'll start by adding some CSS to the styles.css
file.
:root {
.notification-bg {
--mdc-snackbar-container-color: red;
}
}
And then when we pop a snackbar notification we can use the panelClass
option to set the custom CSS style.
import { Component, inject } from '@angular/core';
import {
MatSnackBar,
MatSnackBarAction,
MatSnackBarActions,
MatSnackBarLabel,
MatSnackBarRef,
} from '@angular/material/snack-bar';
import { MatButtonModule } from '@angular/material/button';
import { MatInputModule } from '@angular/material/input';
import { FormsModule } from '@angular/forms';
import { MatFormFieldModule } from '@angular/material/form-field';
@Component({
selector: 'snack-bar-annotated-component-example',
templateUrl: 'snack-bar-annotated-component-example.html',
styleUrl: 'snack-bar-annotated-component-example.css',
standalone: true,
imports: [MatFormFieldModule, FormsModule, MatInputModule, MatButtonModule],
})
export class SnackBarAnnotatedComponentExample {
private _snackBar = inject(MatSnackBar);
durationInSeconds = 5;
openSnackBar() {
this._snackBar.openFromComponent(PizzaPartyAnnotatedComponent, {
panelClass: ['notification-error'],
duration: this.durationInSeconds * 1000,
});
}
}
And our snackbar will look like this. Rather ugly, I know.
And that, my friend, is how to style the background color of an Angular Material snackbar.
Angular + Material = 🥰
Daniel Kreider