Route Guard

Route guards in Angular are used to control access to routes based on certain conditions or criteria. They allow you to prevent navigation to a route, activate a route, or load a component based on the result of an asynchronous operation or some predefined logic.

Angular route guards can be used to control whether the user can navigate to or away from a route based on a given condition.

Why Route Guard

Allowing the users to navigate to all parts of the application is not a good idea and we need to restrict the use from accessing certain routes, until the user performs a specific action like login to application. So, you can use route guards for following scenario's

  • Restrict a use from accessing a route.
  • Ask user to save changes before moving away from view.
  • Validating the route parameters before navigating to the route.
  • Fetch some data before you display component view of a route.

Type of Route Guard

1 CanActivate

This guard decides if a route can be accessed by a user or not. This guard is useful in the circumstances where the user is not authorized to navigate to the target component.

2 CanActivateChild

This guard decides, if a user can leave a route or not. This guard is useful in case where the user might have some pending changes, which was not saved.

3 CanDeactivate

This guard determines whether a child route can be activated or not.

4 Resolve

This guard delays the activation of the route until some tasks are complete. You can use the guard to pre-fetch the data from the backend API, before activating the route.

5 CanLoad

This CanLoad Guard prevents the loading of the Lazy Loaded Module. We generally use this guard when we do not want to unauthorized user to be able to even see the source code of the module.