Tutorial

Angular Router: Navigation Using RouterLink, Navigate, or NavigateByUrl

Updated on January 26, 2021
Default avatar

By Alligator.io

Angular Router: Navigation Using RouterLink, Navigate, or NavigateByUrl

Introduction

In Angular, RouterLink is a directive for navigating to a different route declaratively. Router.navigate and Router.navigateByURL are two methods available to the Router class to navigate imperatively in your component classes.

Let’s explore how to use RouterLink, Router.navigate, and Router.navigateByURL.

A typical link in HTML looks like this:

<a href="/example">
  Example HTML link.
</a>

This example link will direct the user to the /example page.

However, a single page application (SPA) does not have different pages to link to. Instead, it has different views to display to the user. To allow a user to navigate and change the view, you will want to use the RouterLink directive instead of href:

<a routerLink="/users/sammy">
  Link that uses a string.
</a>

This RouterLink example will direct the user to the component at /users/sammy.

The different URL segments can also be passed in an array like this:

<a [routerLink]="['/', 'users', 'sammy']">
  Link that uses an array.
</a>

These two examples are formatted differently but will be directed to the same component at /users/sammy.

Relative Paths

You can use '../ to go up to higher levels in the navigation using something like this:

<a [routerLink]="['../', 'posts', 'sammy']">
  Link that goes up a level.
</a>

In that example, if the user is at /users/sammy, the navigation will change to /posts/sammy.

It is possible to prepend the first URL segment with a ./, ../, or no leading slash.

Parameters

You can pass in parameters to the navigation with an object in the list of URL segments:

<a [routerLink]="['/', 'users', {display: 'verbose'}, 'sammy']">
  Link with parameter.
</a>

In that example, the Router will navigate to /users;display=verbose/sammy.

Named Outlets

You can tell the Router what to place in a named outlet with something like this:

<a [routerLink]="['/', 'users', { outlets: { side: ['sammy'] } }]">
  Link with a side outlet.
</a>

In that example, the sammy segment will be placed in the outlet named side.

It is also possible to tell the Router what to place in multiple named outlets with something like this:

<a [routerLink]="['/', 'users', { outlets: { side: ['sammy'], footer: ['sharks'] } }]">
  Link with a side and footer outlets.
</a>

In this example, the sammy segment will be placed in the outlet named side and the sharks segment will be placed in the outlet named footer.

Using Router

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 resolves 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.

To use either method, you’ll first want to make sure that the Router class is injected into your component class.

First, import Router into your component class:

import { Component } from '@angular/core';
import { Router } from '@angular/router';

Then, add Router to the dependencies:

@Component({
  // ...
})
export class AppComponent {

  constructor(private router: Router) {
    // ...
  }

  // ...
}

Now, you can use Router.navigate or Router.navigateByUrl.

Router.navigate

You pass in an array of URL segments to Router.navigate.

Here’s a basic example using the Router.navigate method:

goPlaces() {
  this.router.navigate(['/', 'users']);
}

And here’s an example demonstrating how Router.navigate is thenable:

goPlaces() {
  this.router.navigate(['/', 'users'])
    .then(nav => {
      console.log(nav); // true if navigation is successful
    }, err => {
      console.log(err) // when there's an error
    });
}

If Router.navigate is successful in this example, it will display true. If Router.navigate is unsuccessful in this example, it will display an error.

Router.navigateByUrl

Router.navigateByUrl is similar to Router.navigate, except that a string is passed in instead of URL segments. The navigation should be absolute and start with a /.

Here’s a basic example using the Router.navigateByUrl method:

goPlaces() {
  this.router.navigateByUrl('/users;display=verbose/sammy');
}

In this example, Router.navigateByUrl will navigate to /users;display=verbose/sammy.

Conclusion

In this article, you learned about navigation in Angular applications. You were introduced to RouterLink, Router.navigate, and Router.navigateByURL.

If you’d like to learn more about Angular, check out our Angular topic page for exercises and programming projects.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
Alligator.io

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
1 Comments


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Very helpfull article

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel