Member-only story

Angular Deep Dive into CanDeactivate Route Guard

Piyush Jain
5 min readMar 24, 2022

--

Angular Route Guard — CanDeactivate

What is CanDeactivate

In this article, we’ll learn about the CanDeactivate router guard. Router guard is a browser event that's used to warn users that they're about to leave a page.

You can use the CanDeactivate guard to prevent users from accidentally leaving a route/page in your application. For example if such page contains a text editor with unsaved changes or an unsubmitted form. You can let the user know they can’t leave the component yet by using a confirmation or alert before the navigation to the other route takes place using the Angular CanDeactivate route guard.

In this article, you’ll see how to use the Angular CanDeactivate guard by example. CanDeactivate is a TypeScript interface that needs to be implemented by a component to create a route guard. This guard will be used by the router to decide if the route can be deactivated. It can be implemented in any Angular component using the canDeactivate method of the interface.

Let’s see how to implement CanDeactivate step by step with Angular 10.

Step 1 — Creating the CanDeactivate Route Guard Service

ng generate guard guards/can-deactivate

--

--

Piyush Jain
Piyush Jain

Written by Piyush Jain

An avid front-end technologist with 9+ years of web industry experience. Self-motivated professional with broad technical skill-set and very strong attention.

Responses (1)

Write a response