Add Custom CSS to Angular MatSnackBar
First, Start a new project in Angular
Open your favourite Editor,
Run ng new <your-application-name>
Install Material Design in your Application,
To install material design, I preferably use Node Package Manager for installing libraries, dependencies etc.
Run, npm install — save @angular/material @angular/animations @angular/cdk
After installation completes, open your app.module.ts file and import MatSnackBarModule as well as BrowserAnimationModule.
Now, Before creating DOM elements, add the styles to styles.css
Note : To make the styling work, CSS should be added to global styles.css
Code for styles.css
.green-snackbar {
background: rgb(65, 252, 134);
color: white;
}.green-snackbar button {
background-color: rgb(65, 252, 134);
color: white;
border: none;
}.red-snackbar {
background: #F44336;
color: white;
}.red-snackbar button {
background-color: #F44336;
color: white !important;
border: none;
}
Imports to be done in app.module.ts File,
.
.
.
import {MatSnackBarModule} from '@angular/material/snack-bar';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
BrowserAnimationsModule,
MatSnackBarModule
], providers: [], bootstrap: [AppComponent]
})
To use MatSnackBar, import MatSnackBar in your respective component.ts file and pass it as a parameter in the constructor. In my case, I’m adding it to app.component.ts.
import { MatSnackBar } from '@angular/material/snack-bar';@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})export class AppComponent{
constructor(private snackBar: MatSnackBar){}// Snackbar that opens with success background
openSuccessSnackBar(){
this.snackBar.open("Login Successful", "OK", {
duration: 3000,
panelClass: ['green-snackbar', 'login-snackbar'],
});
}//Snackbar that opens with failure background
openFailureSnackBar(){
this.snackBar.open("Invalid Login Credentials", "Try again!", {
duration: 3000,
panelClass: ['red-snackbar','login-snackbar'],
});
}
}
Trigger the functions using buttons, Adding two buttons in app.component.html and calling the function on click event.
app.component.html
<button class="btn btn-success" (click)="openSuccessSnackBar()">Success</button><button class="btn btn-danger" (click)="openFailureSnackBar()">Success</button>
Run the application to see the output.