Prevent closing browser tab when form is dirty in Angular 2

我们两清 提交于 2019-12-11 06:49:44

问题


How to prevent closing browser tab when form is dirty in Angular 2?

My html body contains a component:

  <body>
    <my-app>Loading, please wait...</my-app>
  </body>

which contains a router navigation and a router outlet:

<nav>
 (...)
</nav>
<router-outlet></router-outlet>

and when the router navigates to the edit page, I have some form there:

  <form #myForm="ngForm">
    <button pButton type="text" label="Save" (click)="onSave()" [disabled]="!myForm.valid || myForm.pristine"></button>
  </form>

Now, if the form is not 'pristine', I want to ask for confirmation when the user tries to close the browser tab:

window.onbeforeunload = function() {
   if (form.dirty) {
     return "You have unsaved data changes. Are you sure to close the page?"
   }
}

How can I access the dirty state of Angular form in canonical way from there? I could register an event to field change on each field and set the global dirty flag, but I'd have to put that code on every from and by every navigation and then maintain that code so that the message stays consistent. Is there any other way to check out if there's an angular form on the page, which is in dirty state?


回答1:


Perhaps

@HostListener('window:beforeunload', ['$event'])
handleBeforeUnload(event) {
  if (connected) {
    return "You have unsaved data changes. Are you sure to close the page?"
  }
}



回答2:


Simply you can use Jquery to get state of ng-form.

@HostListener('window:beforeunload', ['$event'])
beforeUnloadHandler(event) {
   if($('form').hasClass('ng-touched')) { //You can check with ng-dirty based on your requirements.
        let confirmMessage = 'You have unsaved data changes. Are you sure to close the page?'
        event.returnValue = confirmMessage;
        return confirmMessage;
   }

}

In my case am just showing warning dialog if that the form has been touched.




回答3:


Try this directive https://github.com/extremeprog-com/ng-prevent-navigation.

So it should be simple

<div ng-prevent-navigation="vm.pageShouldBeReloaded"
     ng-prevent-navigation-text="Payment form has unsaved changes. 
        If you leave the page now you will lose those changes."
></div>


来源:https://stackoverflow.com/questions/40719711/prevent-closing-browser-tab-when-form-is-dirty-in-angular-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!