Angular 5 Material Snackbar panelClass config

angularangular-materialtypescript

I am trying to add a panelClass config to the Angular Material Snackbar.

I wrote the following code, by following documentations from the official websites.

import { Component, OnInit } from '@angular/core';
import { MatSnackBar, MatSnackBarConfig } from "@angular/material";
import { Location } from '@angular/common';

@Component({
  selector: 'snack-bar-component-example',
  templateUrl: './snack-bar-component-example.html',
  styleUrls: ['./snack-bar-component-example.css']
})
export class SnackBarComponentExample implements OnInit {

  constructor(public snackBar: MatSnackBar) { }

  ngOnInit() {
  }

  saveButtonClick = () =>{
    this.snackBar.open("This is a message!", "ACTION", {
      duration: 3000,
      panelClass: ["font-family:'Open Sans', sans-serif;"]
    });
  }
}

I have already binded the event to the HTML Button.When I am removing the panelClass config, then the duration config is working fine.
I am importing a Google Font (Open Sans) and trying to apply the font to the Snackbar. However, I am receiving an error:

ERROR DOMException: Failed to execute 'add' on 'DOMTokenList': The token provided ('font-family:'Open Sans', sans-serif;') contains HTML space characters, which are not valid in tokens.

Maybe, I am not able to understand how to use panelClass. Even, when I am trying to add this,

panelClass: ["color:white;"];

It is still showing the error:

ERROR DOMException: Failed to execute 'add' on 'DOMTokenList': The token provided ('color: white;') contains HTML space characters, which are not valid in tokens.

How can I fix this error and get things working? Please help.

PS: I am aware with the extraClasses config. But, I don't want to use it as it is written in the documentation that it will soon be deprecated.

PPS:: It is working fine with the duration config.

Best Answer

In your component SnackBarComponentExample try:

saveButtonClick = () =>{
  let config = new MatSnackBarConfig();
  config.duration = 5000;
  config.panelClass = ['red-snackbar']
  this.snackBar.open("This is a message!", "ACTION", config);
}

Where 'red-snackbar' is a class in your apps main styles.css file. Strangely I was unable to get the config.panelClass to work when I was referencing my components associated css file, but once I put the class into the main styles.css file my styles were applied correctly to the snackBar.

Related Topic