1

I want to build a Web Application which has a form that it's shared in multiple tabs. The functionality I want to implement is to prevent the user from reloading the page when the form is dirty. I tried CanDeactivate Guard, but it's useful only when the user navigates away. So, I tried this implementation like this:

@HostListener('window:beforeunload', ['$event']) onBeforeUnload(event) {

    if (this.parentForm.dirty) {
      this.parentForm.form.markAsPristine();
      this.parentForm.form.markAsUntouched();
      return false;
    }

}

With this in place, I managed to prevent the user to reload, but the browser message is ugly: Browser Message

Is there another way to accomplish the functionality I want with a more beautiful way?

kkaragki
  • 150
  • 2
  • 16
  • If you are using reactive forms you can try something like this `this.parentForm.markAsPristine(); this.parentForm.markAsUntouched();` – Bogdan B Jun 10 '19 at 09:36
  • @BogdanB Thanks for your answer! That was helpful. But generally, what I meant was that I want to implement all this logic in another way (e.g. by displaying a modal) and not by showing an ugly browser message. – kkaragki Jun 10 '19 at 09:45
  • 2
    Depends on your navigation event, if you are navigating inside your app you can leverage the [CanDeactivateGuard](https://angular.io/guide/router#candeactivate-handling-unsaved-changes). For navigation outside of your app (e.g. browser close, navigate to other pages) there is no better way. – Daniel Habenicht Jun 10 '19 at 09:53
  • @DanielHabenicht That was what I was afraid of. :/ Anyway, thanks for your answers. – kkaragki Jun 10 '19 at 09:56

0 Answers0