Basic Routing in Angular

Reading Time: 3 minutesWe use routing to separate different parts of our app, generally (but not always) by using the URL to denote our location. Angular’s router is super easy to use, and below I’ll share some of the basics.

The idea is that we might put our login page at the URL /login and our dashboard page at /dashboard. In Angular, we’d have a LoginComponent for the /login page and a DashboardComponent for the /dashboard page. In the common case, a router lets us map these URLs to a component.

There are three main components that we use to configure routing in Angular:

  • Routes describes our application’s routes
  • RouterOutlet is a “placeholder” component that gets expanded to each route’s content
  • RouterLink is used to link to routes

Routes

Routes is an object that we use on our application component that describes the routes we want to use. For instance, we could write our routes like this:

const routes: Routes = [
  { path: '', redirectTo: 'home', pathMatch: 'full' },
  { path: 'home', component: HomeComponent },
  { path: 'login', component: LoginComponent },
  { path: 'dashboard', component: DashboardComponent }
];

Notice here that we:

  • use path to specify the URL
  • we specify the component we want to route to
  • we can redirect using the redirectTo option

Providing our Router

To install our router into our app we use the RouterModule.forRoot() function in the imports key of our NgModule:

@NgModule({
  declarations: [
    RoutesDemoApp,
    HomeComponent,
    LoginComponentComponent,
    DashboardComponent
  ],
  imports: [
    BrowserModule,
    RouterModule.forRoot(routes) // <-- installs Router routes, components and services
  ],
  bootstrap: [ RoutesDemoApp ],
  providers: [
    provide(LocationStrategy, {useClass: HashLocationStrategy})
  ]
})
class RoutesDemoAppModule {}

// bootstrap our app
platformBrowserDynamic().bootstrapModule(RoutesDemoAppModule)
  .catch((err: any) => console.error(err));

Notice that we give our routes as the argument to RouterModule.forRoot().

When we put RouterModule in our imports it means that we’re able to use the RouterOutlet and RouterLink components in this module. Here’s what each of those do:

RouterOutlet

The RouterOutlet directive tells our router where to render the content in the view.

For instance, if we have a view:

@View({
  template: `
  <div>
    Stuff in the outer template here
    <router-outlet></router-outlet>
  </div>
 ` 
})

Then whenever we switch routes, our content will be rendered in place of the router-outlet tag. That is, if we were switching to the /login page, the content rendered by the LoginComponent would be placed there.

If we want to navigate between routes, we use the RouterLink directive. So if we wanted to link to our login and dashboard page from a navigation, we could change our view above to something like this:

@View({
  template: `
  <div>
    <nav>
      <a>Navigation:</a>
      <ul>
        <li><a [router-link]="['home']">Home</a></li>
        <li><a [router-link]="['login']">Login</a></li>
        <li><a [router-link]="['dashboard']">Dashboard</a></li>
      </ul>
    </nav>

    <router-outlet></router-outlet>
  </div>
 ` 
})

If you’ve used ui-router before, you’ll notice that router-link is similar to the ui-sref directive.

The argument to router-link is an array with the route name as the first element (e.g. "['home']" or "['about']"). This indicates which route to navigate to when we click the element. Notice that we put the name of the route here and not the URL.

It might seem a little odd that the value of router-link is a string with an array containing a string ("['home']", for example). This is because there are more things you can provide when linking to routes, but we’ll look at this into more detail when we talk about child routes and route parameters in the book.

Locating the imports

To find all of the constants we used above, we use the following:

import {
  NgModule,
  provide,
  Component
} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
import {
  RouterModule,
  Routes,
} from '@angular/router';
import {LocationStrategy, HashLocationStrategy} from '@angular/common';

Summary

There we go! That’s more-or-less all the basics you need to know to get routing up and running for Angular.

In the book we cover more sophisticated concepts like nested routes, protected routes, route lifecycles, query parameters etc. Each one of those concepts is part of a full, runnable sample app. So definitely check out the code samples!