1

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.

Marek
  • 63
  • 2
  • 10
  • You can chem this link https://stackoverflow.com/questions/47560696/angular-5-and-material-how-to-change-the-background-color-from-snackbar-compon – Hitech Hitesh Oct 04 '19 at 11:15

1 Answers1

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