Angular – How to check the dismiss reason with an Angular Material snackbar

angularangular-material2snackbar

In the snackbar example on the Angular Material documentation the action is set to undo. I also want an undo snackbar.

But there is one problem. The afterDismissed event is fired when the dismiss button is clicked, but also when the duration has passed. So my form clear button will clear the form and show the snackbar, but after 5 seconds the input is back.

Is there a way to check if the dismiss is called by the undo button? I don't want to use a custom Snackbar because I have to remake the snackbar design…

Best Answer

When you subscribe to the afterDismissed event you should be able to get whether that event came from the snack bar action or not.

So for example if you open your snackbar:

const snackBarRef = this.snackBar.open('Dummy message', 'Undo', {duration: 5000});

Then subscribe to the event:

snackBarRef.afterDismissed().subscribe(info => {
  if (info.dismissedByAction === true) {
    // your code for handling this goes here
  }
});
Related Topic