Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 456
MatterOfFact Avatar asked Mar 20 '26 00:03

MatterOfFact


2 Answers

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);
    });
  }

}
like image 185
Vizjerai Avatar answered Mar 22 '26 23:03

Vizjerai


I had the almost the same error , but my snacbar show in outside my parent component. In devtools I had warning thad said me - my material version not coincide with angular cdk version - than i update my material to latest and it works fine

like image 39
John Avatar answered Mar 22 '26 22:03

John



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!