MatSnackBar panelClass doesnt read styling class

Viewed 7672

I want to insert a scss class into MatSnackBar panelClass. but it didnt working. fyi, the verticalPosition & horizontalPosition work fine. heres my TS:

 openSnackBar(message: string, action: any) {
    this.snackBar.open(message, action, {
      duration: 2000,
      verticalPosition: 'top',
      horizontalPosition: 'center',
      panelClass: ['alert-red'],
    });
 } 

and heres my Scss:

.alert-red{
  padding: 20px;
  background-color: red;
  color: white;
}
3 Answers

EDIT: It seems to work if you prefix your class with the following ::ng-deep snack-bar-container (see this comment). So your component SCSS file should look like this:

::ng-deep snack-bar-container.alert-red{
  padding: 20px;
  background-color: red;
  color: white;
}

WORKAROUND: See post here, it seems that you need to put the style in your applications styles.scss file and not in your components SCSS file.

Check this stackblitz, the style works in the styles.scss, but not when you comment it out and leave it in the app.component.scss. Not sure if this is a bug or intended behaviour.

You have to set encapsulation property for the component:

Like :

import { ViewEncapsulation } from '@angular/core'; // import ViewEncapsulation from core

@Component({
  encapsulation: ViewEncapsulation.None  // Set ViewEncapsulation.None for encapsulation property
})

and add CSS classes in HTML file as:

this.snackBar.open("message", {
      panelClass:['customClass']
});

In CSS file:

.customClass{
  color: red;
}

Working Demo

I had the same issue, I just added !important after the properties defined in my css class to override some default styling. So like:

    .alert-red{
      padding: 20px !important;
      background-color: red !important;
      color: white !important;
    }
Related