Angular Router 12: Can Deactivate Guard

Yuvaraj S
2 min readDec 18, 2022

--

In the previous Blog, We discussed about guards, types of guards and canActivate guards. Please find the link for the lesson.
Angular Router 11: Can Activate Guard Made Easy

CanDeactivate Guard

Can Deactivate route is called when we navigate away from the component 👉. The speciality🌟 of the CanDeactivate guard is except you cannot route away from your current router. Like you cannot navigate away, you are locked 😆

Let’s see how to create a can Deactivate Guard. We will build a message route, where the user needs to give a message before navigating away from the route.

Check the live working project here,
https://stackblitz.com/edit/angular-can-deactive

First, on first I have created 3 Component as Follows,

  • login: just a basic component with no login functionality
  • message: Main functionality which includes where user needs to provide some message navigate away from the router.
  • profile: Just a success message

Create a guard canDeactivate.
CanDeactivate guard should be implemented to one class, since it is implementing we will use canDeactivate method, it takes three parameter. Component, activatedRouteSnapshot and routerstatesnapshot.

Since it’s taking a component we can take a component, in that case, our guard will be working with one particular component. Hence I created an Interface named CanComponentDeactivate. Where we can implement this to any of our components.
If the canDeactivate router returns true it allows to navigate away. Otherwise it will stay in same route.

After Creating routeGuard, Provide it in provider section of the app.module.ts

Next in app.routing.module we have to attach our guard in the router we wanna use canDeactivate to our router. Here I have attached in message router.

Since we made a generic canDeactivate guard, in message.component.ts we have to use the interface so that we can communicate to our canDeactivate guard.
We implemented our canComponentDeactivate interface. Use the method deactivate() that is coming from the Interface. The logic goes like this whenever the message exist we will throw a confirm window alert confirmly you entered a message. If yes we redirect to next route.

Check the live working project here,
https://stackblitz.com/edit/angular-can-deactive

In Next Blog

Angular Router 13: Can Activate Child Guard

— — — — — — — — — End Of Lecture — — — — — — —

Check All lessons of Angular Intermediate Lessons

https://medium.com/@yuvayuvaraj720444/angular-intermediate-lessons-acbea2dfc9b

--

--

Yuvaraj S

Passionate Angular Developer. I post programming content regarding, Frontend Development with working example. ie, Angular, Html, CSS, Javascript