🚀 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!

--

--

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