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(...);
}
}
There's another method on the router that you can use - navigate:
router.navigate(['/inbox/33/messages/44'])
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.