Angular – When using MatBottomSheet how can one close the sheet on browser back

angularangular-material

As the title says, I am using https://material.angular.io/components/bottom-sheet/overview. When the bottom sheet is open and the user clicks on the back button of his browser he is being navigated away from the page that opened the Bottom Sheet. Instead I would simply like to to close the Bottom Sheet on 'browser back'.
What would be the best way (if any) to achieve this in Angular 5/6?

Best Answer

I worked around this by using a "fake route" via "#" link:

this.location.go("#");
let sheet = this.bottomSheet.open(MyBottomSheetComponent, {
  data: { someData: someData },
});
let subscription = this.location.subscribe(x => {
  if (x.url === 'this_is_the_URL_you_are_coming_from') {
    sheet.dismiss(true);
  } else {
    subscription.unsubscribe();
  }
});
sheet.afterDismissed().subscribe(x => {
  if (!x) {
    this.location.back();
  }
});

This "technique" can also be used for angular material's dialog component. It doesn't look very idiomatic to me, so if someone has an easier way of doing this, please post an answer!

Related Topic