🚀 Introducing the CanMatch Router Guard In Angular

Netanel Basal
Netanel Basal
Published in
2 min readJun 15, 2022

Angular provides the canLoad and canActivate router guards. CanLoad and canActivate guards are used to determine if a lazy-loaded module or component should be loaded and activated, respectively.

Using these guards has two drawbacks. The first is that you usually have to define both. Furthermore, there is no easy way to define multiple routes with the same path that can be activated based on certain conditions.

Luckily, a new powerful guard addresses these issues in the next version of Angular— the CanMatch guard.

The CanMatch guard would control whether we can use the route and, as a side effect, whether we can download the code. In addition, when one of the defined guards returns false, the route is skipped, and other routes are processed instead.

We can, for example, use the CanMatch guard to load different components based on a feature flag. Currently, we need to do what I explained in one of my previous articles:

Now, we can do the following:

When the guard function returns true, it’ll load and activate the new todos version; otherwise, the legacy version will be used.

Alternatively, we can return a URL tree or redirect to another route.

We can also use this technique to load different components based on the user role.

Follow me on Medium or Twitter to read more about Angular and JS!

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Netanel Basal
Netanel Basal
Netanel Basal
Netanel Basal

Written by Netanel Basal

A FrontEnd Tech Lead, blogger, and open source maintainer. The founder of ngneat, husband and father.

Responses (7)

Write a response

This is still not present on v 14, right? Is this coming with the next major version?

Can you make small example of how returning an UrlTree can redirect in the same way?

I usually use canActivate, but now I want to try this way. Thanks

Recommended from Medium

Lists

See more recommendations