Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

angular

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?

like image 948
Abraham Avatar asked Nov 24 '16 11:11

Abraham


People also ask

What is routing guard in Angular?

What Are Route Guards? Angular route guards are interfaces provided by Angular which, when implemented, allow us to control the accessibility of a route based on conditions provided in class implementation of that interface.

How does Angular determine routing change?

Steps to detect route change in Angular application Urls. Import Router, Event, NavigationStart, NavigationEnd, NavigationError from '@angular/router'. And inject router in the constructor. Subscribe to the NavigationStart, NavigationEnd, NavigationError events of the router.

Is ngOnDestroy called on route change?

ngOnDestroy doesn't get called because some components do not get destroyed when navigating to a different route.

What does Activatedroute do in Angular?

ActivatedRoutelink. Provides access to information about a route associated with a component that is loaded in an outlet.


2 Answers

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

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

like image 111
JitHiN N JOsE Avatar answered Oct 18 '22 20:10

JitHiN N JOsE


CanDeactivate can be used for that. You need to pass the status to a service that is accessible to canDeactivate.

like image 25
Günter Zöchbauer Avatar answered Oct 18 '22 19:10

Günter Zöchbauer