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.navigateByUrlis similar to changing the location bar
directly–we are providing the “whole” new URL. Whereas
router.navigatecreates 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 with
router.navigate(['/inbox/33/messages/44'])will result in
'/inbox/33/messages/44(popup:compose)'.
Read more in the official docs.