Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 5 material snackbar is not showing correctly for custom ErrorHandling only, otherwise it works fine

Angular 5 material, material snackbar is not showing correctly for custom ErrorHandling only, otherwise it works fine:

I am trying to show my backend errors using material snackbar, the problem is that the 1st time it is fired, it appears in wrong place (not the bottom middle as it should, but up to the left) & it stays there forever without disappearing (it should automatically disappear after 2 seconds as per my configuration)

For the next times it appears, it will appear correctly & disappear after the 2 seconds.

Please try the issue here: stackblitz example showing my issue.

The stackblitz code is here

Thanks

like image 985
Ahmed Elkoussy Avatar asked May 16 '18 13:05

Ahmed Elkoussy


1 Answers

It took me ages to find the answer, I am not very sure why it works like this but it does work, so I hope it helps someone else.

We have to use something called NgZone when calling the material snackbar in the ErrorHandler (I think due to ErrorHandler being called in some special manner in Angular)

So the code calling the snackbar should be:

constructor(private matSnackBar: MatSnackBar, private zone: NgZone, private dataService: DataService) { }
notify (message: string) {
    this.zone.run(() => {
      this.matSnackBar.open(message, '' , {
        duration: 2000
      });
    });
  }

Updated Stackblitz that is now working

like image 120
Ahmed Elkoussy Avatar answered Oct 22 '22 21:10

Ahmed Elkoussy