角度:如果视图中发生任何更改,请防止更改路线 [英] Angular: Prevent route change if any changes made in the view

查看:58
本文介绍了角度:如果视图中发生任何更改,请防止更改路线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在视图中有一个表单(角度).当用户尝试从那里导航时,我希望出现确认消息.我该怎么办?

If I have a form in a view (Angular). When user tries to navigate away from there, and I want a confirmation message to appear. How can I do that?

推荐答案

您可以使用像这样的打字稿来实现canDeactivate

You can implement canDeactivate using typescript like

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

这篇关于角度:如果视图中发生任何更改,请防止更改路线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆