Member-only story
Angular Deep Dive into CanDeactivate Route Guard

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