Angular 8 Cancel or do something before navigation starts

angular router cancel navigation
angular navigation triggers
angular/router events
angular/router navigate with params
angular 5 prevent navigate away
angular resolve guard
angular route to another page
routing angular 8

I have a scenario where I have a route

<a routerLink="/crisis-center" routerLinkActive="active">Crisis Center</a>

in the controller I would like to cancel the rout navigation based on a value.

export class HeroListComponent implements OnInit {
 cancelRoute : boolean = true

  constructor(
   //some logic where before the route is navigated to, I want it to cancel the route
   // and log a message to console
   //console.log('successfully, canceled route');
  ) {}

EDIT

I do not want this done through a Route Guard, i want this done at the component level. I have a component on the page, that I want to cancel route navigation.

here is my use case.

I have a page which hosts multiple components, If someone leaves the page I want to check with component A and make sure there isnt any unsaved data before they navigate away.

EDIT 2

"I do not want this done through a Route Guard". Why? This is essentially what the CanDeactivate guard exists for. You can definitely use it for your use case with ease.

Correct me If I am wrong, but I would need to put the CanDeactivateGuard On every route for example

RouterModule.forRoot([
  {
    path: 'team/:id',
    component: TeamComponent,
    canDeactivate: ['canDeactivateTeam']
  }

I do not want to have a CanDeactivate on every route, when Only 1 route have foo component inside.

There are many routes, only one route needs foo component and he need to can cancel the route navigation. As far as I know the canDeactivate route gaurd cannot access components created on a route.

EDIT 3

NavigationStart The docs state that this is an event that is fired. I can hook into that event, but I cannot stop the actually navigation. Unless I am wrong NavigatonStart just tells me when it starts navigating not how to stop the navigation.

But PLEASE no down arrow down for me. There is no other way to prevent from navigate with no DeactivateGuard, but! You can make him as injectable.

import { CanDeactivate } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { Injectable } from '@angular/core';

@Injectable()
export class DeactivateGuard implements CanDeactivate<HomeComponent> {

    canDeact = true

  canDeactivate() {
    return this.canDeact
  }
}

You can inject it to any component You want and change canDeact to false so You prevent from navigate to other route when job is not done. Still, on default canDeact is true, so if in your route there will be no component foo with will trigger ngOnInit which make guard false and prevent from navigate out.

so guard as above and setup canDeactivate in routing:

{
    path: 'team/:id',
    component: TeamComponent,
    canDeactivate: [DeactivateGuard]
}

Becouse of it is injectable provide it in some root module:

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule
  ],
  providers: [
    DeactivateGuard
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Assuming, some times foo component will be inside TeamComponent. Just in foo component:

export class FooComponent implements OnInit {

  constructor(private deactGuard: DeactivateGuard) { }

  ngOnInit() {
    this.deactGuard.canDeact = false
  }

  jobDone() {
    this.deactGuard.canDeact = true
  }

}

Try to not paste foo component outside of TeamComponent range. Or develop it correct in ngOnInit so he will not make canDeact false when ever he want's to.

Angular 8 Cancel or do something before navigation starts, You can inject it to any component You want and change canDeact to false so You prevent from navigate to other route when job is not done. Still, on default canDeact is true, so if in your route there will be no component foo with will trigger ngOnInit which make guard false and prevent from navigate out. 2 Angular 8 Cancel or do something before navigation starts Oct 8 '19 2 Angular 4 img src is not found Jan 3 '19 View all questions and answers →

Edit based on the comment below: One possible solution would be the following: Change X.component.html to:

<a (click)='goToCrisisCenter()' routerLinkActive="active">Crisis Center</a>

X.component.ts

constructor(private navigationService: NavigationService) {}

goToCrisisCenter() {
  this.navigationService.tryNavigateTo('/crisis-center');
}

Create NavigationService with:

canNavigate = true;
tryNavigateTo(route:string) {
  if(canNavigate) this.router.navigate([/crisis-center])
}

Inject NavigationService in HeroListComponent and manipulate canNavigate as it suits you.

NavigationCancel, An event triggered when a navigation is canceled, directly or indirectly. See more​ class NavigationCancel extends RouterEvent { constructor(id: number, url:  Sometimes, In place of starting an independent execution for every subscriber, we want each subscription to get the same values-even if values have already begun to emit. Let’s see an example that counts from 1 to 3, with a one-second delay after each number emitted.

Try this:

import { Router } from '@angular/router';


export class HeroListComponent implements OnInit {
 cancelRoute : boolean = true

  constructor(provate router: Router) {
   if (cancelRoute) {
     this.router.navigate(["/yourRoute"]);
   } else {
     this.router.navigate(["/yourRouteElse"]); 
   }
}
// If you don't want me to do something the `else`, leave it empty.

I leave you a documentation: https://www.techiediaries.com/angular-router-routerlink-navigate-navigatebyurl/

angular/angular, Once the route change starts we are unable to pause the route Angular version​: 5.2.8 Browser: All browsers For Tooling issues: You would only redirect navigation to /cancel-navigation to do the canceling. The events fired are executed synchronously and the router ignores anything done inside them  In this post, we are going to go through a complete example of how to build a custom dialog using the Angular Material Dialog component. We are going to cover many of the most common use cases that revolve around the Angular Material Dialog, such as: common dialog configuration options,

Developer Guide: Component Router, The Root Router is the starting point for all navigation. You can access this Router by injecting the $rootRouter service. We define the top level Root Component  Different approaches to managing RxJS subscriptions in Angular applications lead to different trade-offs in terms of verbosity, robustness or simplicity. Let’s explore our options together!

Angular Routing: How to Display a Loading Indicator When , Notifying the user that something is happening in the background can We will start with a sample application that looks like this: before the start of every navigation, and hide it when the navigation is complete. if an error occurs ( NavigationError ), or if the navigation is cancelled ( NavigationCancel ). Angular Router: A Complete Example (build a Bootstrap Navigation Menu) Last Updated: 24 April 2020 local_offer Angular Router In this post, we are going to learn how to use several features of the Angular Router in order to build a navigation system with multiple navigation levels, similar to what you would find in an online learning platform or an online store like Amazon (but simpler).

Angular Router Fundamentals: Child & Auxiliary Routes, Master Detail, The first thing that we should do is simply write some routing configuration. if you navigate to /home then the Home component gets displayed; if you But here is where for new users of the router things might start to go wrong. This gives the exact same result as before: only /home or /lessons can be  Having a confirmation dialogs is a very common requirement in the applications nowadays. They are used when a specific(in most cases destructive) action is executed, like deleting a specific record.

Comments
  • This is done outside of the component. You are looking for a Route Guard.
  • How about using NavigationStart of Router event?
  • Also I think you mean to write component instead of controller.
  • See also angular.io/guide/router#canactivate-requiring-authentication as an example of how to do this.
  • "I do not want this done through a Route Guard". Why? This is essentially what the CanDeactivate guard exists for. You can definitely use it for your use case with ease.
  • This seems like a good answer to my needs. Can you show me what the route would look like and How I would wire this up? If not thats cool too and i can try and figure it out
  • @gh9 Yeah i can.
  • Sweet, thanks very much! You sir deserve more up votes hopefully this question will generate more for you.
  • @gh9 Updated. Don't think Will generate more.
  • No worries i can make it work from here, thanks so much!