Protecting Angular v2+ Routes with CanActivate/CanActivateChild Guards

Protecting Angular v2+ Routes with CanActivate/CanActivateChild Guards

Protecting routes is something that has to happen in any app with authentication. There will be sections of your applications that you don't want certain users to get to.

We'll be looking at a simple example of how to use Angular router guards to protect an area of our site. While this will be a simple example that you can reference back to, we'll look at more advanced setups in future articles.

In this tutorial, we'll look at how we can use Angular guards to:

[…]

To create a guard using the Angular CLI, use:

[…]

In the canActivate() method, we can do any checks we need to check if a user has access. Return a boolean true/false. Also, this is where you can handle routing users away from a route if they don't have access.

Import this new class into a module so your app knows how to grab it. Then you can use this when defining routes:

[…]