0

I have a bootstrap-modal in my application, and would like to be reflected on the browsing history when it's open, so when the user clicks the browser's back button - the modal will close.

I'm familiar with Angular's Location object, so Location.back() and Location.go() works fine for my scenario.

The thing is - once the user clicked the back button, I would like to pop the top path from the browser history, so after closing the modal - the user couldn't reopen it using the browser's "next" button.

Any way to achieve this with Angular's Router / Location / any other Angular-ish way?

yuval.bl
  • 4,890
  • 3
  • 17
  • 31

1 Answers1

0

This is what I use to achieve this. Whenever user clicks on the header component button called 'Post It', it displays a modal dialog. When user clicks the back button, it takes the user to the previous route. Here is my service that handles the opening of the dialog:

import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { PostItDialog } from './post-it-dialog.component';
import { Location } from '@angular/common';
import { MatDialog } from '@angular/material/dialog';`

    public openPostItDialog(dialog: MatDialog): void {
        const dialogRef = dialog.open(PostItDialog, {
          width: '350px'
        });
        const url = this.router.createUrlTree(['posts/new']).toString();
        this.location.go(url);
        console.log("Dialog was open");
    
        dialogRef.afterClosed().subscribe(() => {
          console.log("The dialog was closed");
          this.location.go("");
        })
StvnBrkdll
  • 3,924
  • 1
  • 24
  • 31
O.MeeKoh
  • 1,976
  • 3
  • 24
  • 53
  • `afterClosed` will add another "empty" route, so when the user press the back one more time, It will go back to `posts/new` – yuval.bl Mar 19 '19 at 14:37
  • Mine works as expected. i go from '/login' => '/' => '/posts/new' then I hit back I go to '/' then i hit back again I go to '/login'. Have you actually tried this locally to see the behavior? – O.MeeKoh Mar 19 '19 at 14:59
  • I did. my scenario is: 1. user click to open modal. route goes: `/page => /page(modal)` 2. user click to close modal. route goes: `/page(modal) => /page` So now routing stack is: `/page => /page(modal) => /page` and when the user clicks back - it goes back to the modal route. Moreover, I would like to prevent the user from going forward once the browser's "back" button clicked. I'm starting to doubt it can be achieved with JavaScript. – yuval.bl Mar 20 '19 at 09:08