我使用确认弹出窗口要求用户验证他/她离开页面的操作而不保存更改。
为了在 Angular 7 中实现这一点,代码是这样完成的:
ngOnDestroy() {
if (this.updateProfile) {
if (!window.confirm('Are you sure you wanna leave this page the changes may lost?')) {
this.router.navigate(['/dashboard/profile']); //Currently navigating to the same page
}
}
}
在这种情况下,导航到同一页面看起来不错,但我使用同一页面来查看和编辑详细信息。当我将其重定向到个人资料页面时,默认查看模式已打开。
我想要的是,如果用户单击“取消”弹出窗口,组件不会发生任何更改。
在 Angular 7 中还有其他方法可以实现相同的效果吗?
最佳答案
实现此场景的更好方法 - 使用 Route Guard。
@Injectable()
export class CanDeactivateGuard implements CanDeactivate<UserFormComponent> {
canDeactivate(component: UserFormComponent): boolean {
if(component.hasUnsavedData()){
if (confirm("You have unsaved changes! If you leave, your changes will be lost.")) {
return true;
} else {
return false;
}
}
return true;
}
}
欲了解更多信息,您可以访问链接:
或者
https://www.concretepage.com/angular-2/angular-candeactivate-guard-example
关于javascript - Angular 7 : How to keep component persist when user clicked cancel In confirmation Pop-up,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56881652/