如何防止关闭浏览器选项卡时形式角2脏?
我的HTML体内含有一种成分:
<body>
<my-app>Loading, please wait...</my-app>
</body>
其中包含一个路由器导航和路由器出口:
<nav>
(...)
</nav>
<router-outlet></router-outlet>
当路由器导航到编辑页面,我有某种形式的有:
<form #myForm="ngForm">
<button pButton type="text" label="Save" (click)="onSave()" [disabled]="!myForm.valid || myForm.pristine"></button>
</form>
现在,如果形式不是“原始”,我想请求确认,当用户试图关闭浏览器选项卡:
window.onbeforeunload = function() {
if (form.dirty) {
return "You have unsaved data changes. Are you sure to close the page?"
}
}
如何访问角形式的脏状态正规途径从那里? 我可以注册一个事件,在每个场场变化和设置全局脏标志,但我必须把对每一个代码,并通过在每个导航,然后使信息保持一致维护该代码。 是否有任何其他的方法来检查是否有页面上的一个角的形式,这是在肮脏的状态?
也许
@HostListener('window:beforeunload', ['$event'])
handleBeforeUnload(event) {
if (connected) {
return "You have unsaved data changes. Are you sure to close the page?"
}
}
只要您可以使用jQuery获得的状态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;
}
}
就我而言我只是表示,如果该警告对话框form
已被触碰。
试试这个指令https://github.com/extremeprog-com/ng-prevent-navigation 。
所以它应该是简单
<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>