angular - 角度 - 当用户离开一页(一个组件)时显示警报
问题描述
预期行为
我有一个包含一个表单的页面,当用户想要离开这个页面时,实际上它只是一个组件,我想显示一些警报,比如“你真的要离开这个页面吗?你的更改将不会被保存”。
当前行为
我努力了
@HostListener('window:beforeunload', ['$event']) yourfunction($event) {
return $event.returnValue='Your changes will not be saved';
}
但是对话没有出现。
任何想法或建议都将受到欢迎。
解决方案
这是因为在 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]}
推荐阅读
- google-cloud-platform - GCP API 仪表板不计算我的所有请求
- python - 如果没有命令 python manage.py runcrons,Cron 不会执行我的任务
- vb.net - 两个 VSTO 加载项能否处理相同的 Outlook 应用程序事件 (application.newmailex)
- .net - .NET 正则表达式不正确匹配
- algorithm - 考虑到某些延误,在最坏的情况下到达目的地的最短时间?
- .net-core - Visual Studio 自定义项目模板 - applicationUrl 端口号
- linux - 对不同终端的命令
- angular - 如何使用 MatTabChangeEvent 获取内容
- regex - 使用 REGEX 在 Google Analytics 中为每个会话生成多次转化?
- reactjs - 集成测试 - redux/react + nock.js