Search code examples
angularangular-materialsnackbar

Changing styles of angular material snack-bar after interval


I have created a custom angular material snackbar and I would like to change it's background colour after a time interval (before it closes). So far I have tried the following code, but the background colour does not change as expected. I am new to Angular...any suggestions would be appreciated, thanks.

openSnackBar(isLoading: boolean = true) { 
  this._snackBar.openFromComponent(SnackbarComponent, {
      duration: 5000,
      panelClass: isLoading ? "greenClass" : "blueClass",
  });

  setTimeout(() => {
    isLoading = false;
  }, 2000);
}

I tried to put the setTimeout function inside the ngOnInit() but I was getting an error: Property 'isLoading' does not exist on type 'SnackbarButtonComponent'


Solution

  • Problem with your code is that Property 'isLoading' is not property of snakebar(which directly opens in dom).

    You can achive this by using dom query selector

    openSnackBar() {
        this._snackBar.openFromComponent(SnackbarComponent, {
          duration: 5000,
          panelClass: ['panelClass'],
        });
        setTimeout(() => {
    
           let mysnackbar: any = document.querySelectorAll('.panelClass')[0]; // querying out our panelClass
           mysnackbar.style.cssText += 'background-color: #9b8b8b !important'; // changing value
       
        }, 2000);
      }
    

    remember to add panelClass in your global styles(styles.css file).

    .panelClass {
      background-color: pink; // initial background color
    }
    

    i have created a stackblitz example here