How to use router.navigateByUrl and router.navigate in Angular
navigateByUrl
routerLink
directive as used like this:
<a [routerLink]="/inbox/33/messages/44">Open Message 44</a>
is just a wrapper around imperative navigation using router
and its navigateByUrl method:
router.navigateByUrl('/inbox/33/messages/44')
as can be seen from the sources:
export class RouterLink { ... @HostListener('click') onClick(): boolean { ... this.router.navigateByUrl(this.urlTree, extras); return true; }
So wherever you need to navigate a user to another route, just inject the router
and use navigateByUrl
method:
class MyComponent { constructor(router: Router) { this.router.navigateByUrl(...); }}
navigate
There's another method on the router that you can use - navigate:
router.navigate(['/inbox/33/messages/44'])
difference between the two
Using
router.navigateByUrl
is similar to changing the location bar directly–we are providing the “whole” new URL. Whereasrouter.navigate
creates a new URL by applying an array of passed-in commands, a patch, to the current URL.To see the difference clearly, imagine that the current URL is
'/inbox/11/messages/22(popup:compose)'
.With this URL, calling
router.navigateByUrl('/inbox/33/messages/44')
will result in'/inbox/33/messages/44'
. But calling it withrouter.navigate(['/inbox/33/messages/44'])
will result in'/inbox/33/messages/44(popup:compose)'
.
Read more in the official docs.
router.navigate vs router.navigateByUrl
router.navigate
is just a convenience method that wraps router.navigateByUrl
, it boils down to:
navigate(commands: any[], extras) { return router.navigateByUrl(router.createUrlTree(commands, extras), extras);}
As mentioned in other answers router.navigateByUrl
will only accept absolute URLs:
// This will workrouter.navigateByUrl("http://localhost/team/33/user/11")// This WON'T work even though relativeTo parameter is in the signaturerouter.navigateByUrl("../22", {relativeTo: route})
All the relative calculations are done by router.createUrlTree
and router.navigate
. Array syntax is used to treat every array element as a URL modifying "command". E.g. ".."
- go up, "path"
- go down, {expand: true}
- add query param, etc.. You can use it like this:
// create /team/33/user/11router.navigate(['/team', 33, 'user', 11]);// assuming the current url is `/team/33/user/11` and the route points to `user/11`// navigate to /team/33/user/11/detailsrouter.navigate(['details'], {relativeTo: route});// navigate to /team/33/user/22router.navigate(['../22'], {relativeTo: route});// navigate to /team/44/user/22router.navigate(['../../team/44/user/22'], {relativeTo: route});
That {relativeTo: route}
parameter is important as that's what router will use as the root for relative operations.
Get it through your component's constructor:
// In my-awesome.component.ts: constructor(private route: ActivatedRoute, private router: Router) {} // Example call onNavigateClick() { // Navigates to a parent component this.router.navigate([..], { relativeTo: this.route }) }
routerLink directive
Nicest thing about this directive is that it will retrieve the ActivatedRoute
for you. Under the hood it's using already familiar:
router.navigateByUrl(router.createUrlTree(commands, { relativeTo: route }), { relativeTo: route });
Following variants will produce identical result:
[routerLink]="['../..']"// if the string parameter is passed it will be wrapped into an arrayrouterLink="../.."
In addition to the provided answer, there are more details to navigate
. From the function's comments:
/** * Navigate based on the provided array of commands and a starting point. * If no starting route is provided, the navigation is absolute. * * Returns a promise that: * - resolves to 'true' when navigation succeeds, * - resolves to 'false' when navigation fails, * - is rejected when an error happens. * * ### Usage * * ``` * router.navigate(['team', 33, 'user', 11], {relativeTo: route}); * * // Navigate without updating the URL * router.navigate(['team', 33, 'user', 11], {relativeTo: route, skipLocationChange: true}); * ``` * * In opposite to `navigateByUrl`, `navigate` always takes a delta that is applied to the current * URL. */
The Router Guide has more details on programmatic navigation.