Angular: Prevent route change if any changes made in the view

后端 未结 4 926
余生分开走
余生分开走 2021-02-06 23:31

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?

4条回答
  •  孤城傲影
    2021-02-07 00:11

    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 {
        
        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 {}

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

提交回复
热议问题