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?
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.
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.
ngOnDestroy doesn't get called because some components do not get destroyed when navigating to a different route.
ActivatedRoutelink. Provides access to information about a route associated with a component that is loaded in an outlet.
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
CanDeactivate
can be used for that. You need to pass the status to a service that is accessible to canDeactivate
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With