I want to create a service for Mat Snackbar, so that I have Snackbar available throughout the application. I can get that running thanks to this question - How to use SnackBar on service to use in every component in Angular 2 and I also know I can change the color by adding class with panelClasses in SnackBarConfig. My question is, how could I do it and have it in a service? I do not want to have a component, and I do not know how to have service know the css class I want to user. I know I cannot import scss into ts file. I was thinking about creating a class in app.component.scss and then importing this to each component.scss I want to use the SnackBar in, but that does not work. I am really stuck now and I appreciate any help. Thanks.
Asked
Active
Viewed 353 times
1 Answers
0
Yes, use a service to handle your snackbar then you could do a method like this :
export class SnackbarService {
constructor(private _snackBar: MatSnackBar) {}
public openSnackBarFromComponent(snackbarProps: ISnackbarComponent): void {
this._snackBar.openFromComponent(SnackbarComponent, {
panelClass: snackbarProps.config.panelClass || [''],
duration: snackbarProps.config.duration || 2000,
horizontalPosition: snackbarProps.config.horizontalPosition || 'center',
verticalPosition: snackbarProps.config.verticalPosition || 'bottom',
data: snackbarProps.config.data || {},
});
}
}
So, I made a service with a method that can be call from anywhere, open a component called SnackbarComponent with a specific configuration. In you panelClass, you can add a specific class with a specific background.
I call the method from the SnackbarService like so with my custom snackbar config:
this.SnackbarService.openSnackBarFromComponent({
config: {
panelClass: ['Your customClass'],
data: {
message: 'your msg',
iconClass: 'check-circle',
colorIcon: 'fg_green',
},
},
}),
This is a way but of course, there are many ways to do it and maybe better than this :)

brieucdlf
- 181
- 4
- 13