防止表单在Angular 2中变脏时关闭浏览器选项卡 [英] Prevent closing browser tab when form is dirty in Angular 2

查看:75
本文介绍了防止表单在Angular 2中变脏时关闭浏览器选项卡的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当Angular 2中的表单变脏时,如何防止关闭浏览器选项卡?

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

我的html正文包含一个组件:

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?"
   }
}

如何从那里以规范的方式访问Angular表单的脏状态?我可以在每个字段上注册一个事件以进行字段更改并设置全局脏标志,但是我必须将每个导航程序的每个代码都放在该代码上,然后维护该代码,以使消息保持一致.还有其他方法可以检查页面上是否有角形(处于脏状态)?

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?

推荐答案

也许

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

这篇关于防止表单在Angular 2中变脏时关闭浏览器选项卡的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆