gpt4 book ai didi

Angular:如果在 View 中进行了任何更改,则防止路由更改

转载 作者:太空狗 更新时间:2023-10-29 16:56:23 25 4
gpt4 key购买 nike

如果我在 View 中有一个表单( Angular )。当用户试图离开那里时,我希望出现一条确认消息。我该怎么做?

最佳答案

您可以使用 typescript 实现 canDeactivate

import { Injectable } from '@angular/core';
import { CanDeactivate } from '@angular/router';
import { ViewthatyouwantGuard } from './path to your view';

@Injectable()
export class ConfirmDeactivateGuard implements CanDeactivate<ViewthatyouwantGuard> {

canDeactivate(target: ViewthatyouwantGuard) {
if (target.hasChanges) {
return window.confirm('Do you really want to cancel?');
}
return true;
}

}

// hasChanges - function in 'ViewthatyouwantGuard' which will return true or false based on unsaved changes

// And in your routing file provide root like
{path:'rootPath/', component: ViewthatyouwantGuard, canDeactivate:[ConfirmDeactivateGuard]},

// Last but not least, also this guard needs to be registered accordingly:
@NgModule({
...
providers: [
...
ConfirmDeactivateGuard
]
})
export class AppModule {}

来源:https://blog.thoughtram.io/angular/2016/07/18/guards-in-angular-2.html

关于Angular:如果在 View 中进行了任何更改,则防止路由更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40785716/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com