首页 > 解决方案 > 角度 - 当用户离开一页(一个组件)时显示警报

问题描述

预期行为

我有一个包含一个表单的页面,当用户想要离开这个页面时,实际上它只是一个组件,我想显示一些警报,比如“你真的要离开这个页面吗?你的更改将不会被保存”。

当前行为

我努力了

@HostListener('window:beforeunload', ['$event']) yourfunction($event) {
  return $event.returnValue='Your changes will not be saved';
}

但是对话没有出现。

任何想法或建议都将受到欢迎。

标签: angularangular-formsangular-routerangular-router-guards

解决方案


这是因为在 Angular 中,页面之间的转换不是“真实的”,并且 window.beforeunload 事件不会触发。为了管理这个,你必须使用 Angular 自己的 Router Guards,特别是canDeactivate一个。这是有关守卫的特定文档的链接。canDeactivate您的实际代码可能如下所示:

@Injectable()
class DeactivateGuard implements CanDeactivate<YourComponent> {
    canDeactivate(){
//your popup logic goes here. Note that this method should return 
// a boolean, or a Promise/Observable of a boolean, if any async operations are present
   }
}

创建此守卫后,您只需将其放在您的路由定义中:

{path: 'path-to-your-component', component: YourComponent, canDeactivate: [DeactivateGuard]}

推荐阅读