Sunday, 30 April, 2017 UTC


Summary

In our intro to the Angular router, we briefly saw how to navigate to a different route declaratively using the RouterLink directive. This post builds on that to demonstrate a few more examples, as well as how to navigate imperatively in the component class.
RouterLink
A basic example of using the RouterLink directive can look like this:
<a routerLink="/red-pill/neo">Go!</a>
The different url segments can also be passed in an array like this:
<a [routerLink]="['/', 'red-pill', 'neo']">Go!</a>
You can go up to higher levels in the navigation using something like this:
<a [routerLink]="['../', 'blue-pill', 'neo']">Go!</a>
In that example, if the user is at /red-pill/neo, the navigation will change to /blue-pill/neo.

You can pass-in parameters to the navigation with an object in the list of url segments:
<a [routerLink]="['/', 'red-pill', {x: 'white-rabbit'}, 'neo']"> Param! </a>
With that example, the router will navigate to /red-pill;x=white-rabbit/neo.

Named Outlets

You can tell the router what to place in a named outlet with something like this:
<a [routerLink]="['/', 'red-pill', { outlets: { side: ['neo'] } }]"> Nav with a named outlet </a> 
In that example, the neo segment will be placed in the outlet named side. Here’s another example, where in addition the trinity segment goes in the footer named outlet:
<a [routerLink]="['/', 'red-pill', { outlets: { side: ['neo'], footer: ['trinity'] } }]"> Nav with a named outlet </a> 
Navigating Imperatively
There are two methods available on Angular’s Router class to navigate imperatively in your component classes: Router.navigate and Router.navigateByUrl. Both methods return a promise that resolve to true if the navigation is successful, null if there’s no navigation, false if the navigation fails or is completely rejected if there’s an error.
You pass-in an array of url segments to Router.navigate or a string to Router.navigateByUrl, just like you would using the RouterLink directive.
To use either method, you’ll first want to make sure that the Router class is injected into your component class:
import { Component } from '@angular/core'; import { Router } from '@angular/router'; @Component({ // ... }) export class AppComponent { constructor(private router: Router) {} // ... }

Router.navigate

Here’s a basic example using the navigate method:
goPlaces() { this.router.navigate(['/', 'red-pill']); }
And here’s an example demonstrating how navigate is thenable:
goPlaces() { this.router.navigate(['/', 'red-pill']).then(nav => { console.log(nav); // true if navigation is successful }, err => { console.log(err) // when there's an error }); }

Router.navigateByUrl

Router.navigateByUrl is basically the same as Router.navigate, except that a string is passed-in instead of url segments and the navigation should be absolute and start with a /:
goPlaces() { this.router.navigateByUrl('/red-pill;x=white-rabbit/neo'); }