Search⌘ K
AI Features

Preventing Navigation Away from a Route

Explore how to implement Angular CanDeactivate guards to prevent users from accidentally navigating away from a route, such as a checkout cart, by showing confirmation dialogs. Understand the use of route resolvers to prefetch data and reduce UI flickering when loading product details. This lesson helps you improve navigation control and user experience in Angular applications.

Guards are used not only to prevent access to a route but also to prevent navigation away from it. A guard that controls if a route can be deactivated is a function of the CanDeactivateFn type. We will learn how to use it by implementing a guard that notifies the user of pending products in the cart:

  1. Create a file named checkout.guard.ts inside the src\app folder.

  2. Add the following import statements at the top of the file:

TypeScript 4.9.5
import { CanDeactivateFn } from '@angular/router';
import { CartComponent } from './cart/cart.component';
  1. Create the following checkoutGuard function:

TypeScript 4.9.5
export const checkoutGuard: CanDeactivateFn<CartComponent> = () => {
const confirmation = confirm('You have pending items in your cart. Do you want to continue?');
return confirmation;
};

In the preceding function, we set the type of the CanDeactivateFn function to CartComponent because we want to check whether the user navigates away from this component only.

Note: In a real-world scenario, we may need to create a generic guard to support additional components.

We then use the global confirm method to display a confirmation dialog before navigating away from the CartComponent. ...