angularangular-materialangular7snackbar

Angular Material Snackbar not shown correctly


Stackblitz example

Hi community I implemented a global error handler and a global loading component (angular material spinner) to my angular 7 project. When detecting a HttpErrorResponse the loader should be removed and an angular material snackbar should be shown.

The snackbar should open at the bottom of the page and should close when clicking "x".

But instead it opens at the upper left side.

enter image description here

When clicking "x" it closes and opens again at the expected position. But then it doesn't react to clicks anymore. It disappears after clicking "x" and then clicking a different position of the window.

This behaviour is also shown when removing the loading spinner.

Does anybody has an idea how to solve this issue? Thank you very much.


Solution

  • The issue is that the snackbar is being ran outside of angular's zone.

    A quick fix can be placed in your SnackbarService or where the error method is being called.

    Stackblitz:src/app/services/snackbar.service.ts

    import { Injectable, NgZone } from '@angular/core';
    import { MatSnackBar, MatSnackBarRef, SimpleSnackBar, MatSnackBarConfig } from '@angular/material';
    
    @Injectable({
      providedIn: 'root'
    })
    export class SnackbarService {
    
      constructor(
        public snackbar: MatSnackBar,
        private zone: NgZone,
      ) { }
    
      error(message: string) {
        const config = new MatSnackBarConfig();
        config.panelClass = ['background-red'];
        config.verticalPosition = 'bottom';
        config.horizontalPosition = 'center';
        this.zone.run(() => {
          this.snackbar.open(message, 'x', config);
        });
      }
    
    }