Netanel Basal

Learn development with great articles

Create UrlTree from Any ActivatedRouteSnapshot in Angular

--

In the current Router API version (v14.0.0-), the UrlTree can only be created from an ActivatedRoute, which must both be active and materially appear in the UrlTree (meaning it cannot be an empty path named outlet).

Due to the implementation of the current UrlTree creation process, the UrlSegment of the ActivatedRoute is looked up in the currently active UrlTree of the router. If this doesn’t work, the UrlTree creation fails.

As an example, suppose we have a guard that, based on some condition, redirects to a sibling route:

Because the sibling route has not yet been activated, this will not work. To address this issue, the Router exposes a new function that allows creating a UrlTree from any ActivatedRouteSnapshot:

The CreateUrlTreeFromSnapshot function takes an ActivatedRouteSnapshot, commands, and optional queryParams and fragments and returns a UrlTree.

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

--

--

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 (1)