I have created a global snackBarService in my angular application. I want to customise the panelClass based on the type of message (error, success, warning etc.). The approach I took is to have a global config in the constructor, which helps to define global styles/configurations for the snack bar and will add custom classes to change the background colours based on the message type.
SnackBarService.ts
import { Injectable, NgZone } from "@angular/core";
import { MatSnackBar, MatSnackBarConfig } from "@angular/material";
@Injectable({
providedIn: "root",
})
export class SnackbarService {
private config: MatSnackBarConfig;
constructor(private snackbar: MatSnackBar, private zone: NgZone) {
this.config = new MatSnackBarConfig();
this.config.panelClass = ["snackbar-container"];
this.config.verticalPosition = "top";
this.config.horizontalPosition = "right";
this.config.duration = 4000;
}
error(message: string) {
this.config.panelClass = ["snackbar-container", "error"];
this.show(message);
}
success(message: string) {
this.config.panelClass = ["snackbar-container", "success"];
this.show(message);
}
warning(message: string) {
this.config.panelClass = ["snackbar-container", "warning"];
this.show(message);
}
private show(message: string, config?: MatSnackBarConfig) {
config = config || this.config;
this.zone.run(() => {
this.snackbar.open(message, "x", config);
});
}
}
app.scss
.snackbar-container {
margin-top: 70px !important;
color: beige;
&.error {
background-color: #c62828 !important;
}
&.success {
background-color: #2e7d32 !important;
}
&.warning {
background-color: #ff8f00 !important;
}
}
And from the component I will be using the service like this
this.snackbarService.success("This message is from snackbar!!!");
The above code works perfectly.
But,
Since the panelClass does not have a .push method, I can't add dynamic classes, and because of this, I need to duplicate the global class every time like this this.config.panelClass = ["snackbar-container", "error"];
error(message: string) {
this.config.panelClass.push("error"); // this throws error in typescript
this.show(message);
}
Is there any better way to solve this problem?