3

I have implemented a check for unsaved changes when navigating away from a component in the routing of my Angular5 app. I used the solution suggested by stewdebaker here: Warn user of unsaved changes before leaving page

I am facing a problem with this related to an unresolved issue in Angular that is described here: https://github.com/angular/angular/issues/13586

In summary, what happens is that for example, a user hits the back button, they hit the deactivation guard and respond that "No", they want to stay on the page. Then they hit the back button again and the second time they respond that "Yes" they want to abandon their changes and proceed with the Back navigation. But because the first (rejected) navigation gets remembered in the routing history, they are navigated two steps back in the routing instead of one.

The link above (for the Angular issue) was raised in Dec 2016 and so far there are no updates there on when the issue is going to be fixed, so I was wondering if anyone has come up with any workarounds in the meantime?

Martin Bamford
  • 379
  • 3
  • 13

1 Answers1

0

Before returning false in component, add this.Location.go(this.route.url) . it should fix the issue.

like

import { Location } from '@angular/common'; 
import   router     from '@angular/router';

canDeactivate():Observable<boolean>| Promise<boolean>| boolean {
    return confirm('Do you want to discard the changes?') ? true : (this.Location.go(this._route.url),false);  
}
Stefan Becker
  • 5,695
  • 9
  • 20
  • 30