Basic Routing in Angular

We 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:

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:

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:

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:

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:

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!

  • przemeko

    The content is litte bit outdated 🙂 In latest releases Angular uses providers to setup fe.

    bootstrap(AppCmp, [
    ROUTER_PROVIDERS
    ]);

    and that all. You may use router config in your code.

    • https://ng-book.com/2 Fullstack.io

      Whoops! Yes we’ll fix that

  • Michalis Argyriou

    How about hiding the Login link when you login? How can you achieve this?

    • onewiseburdman

      *ngIf

  • e.wad

    Can you update to angular 2 – RC ?

  • Daniel Lim

    It appears to be broken now, time for an update?

  • Aamir

    ‘ Terminal : true ‘ in redirect method is now deprecated, use pathMatch: “full” instead.

  • Adilson Pedro

    How to put Login Component in a full page, not inside the “”?

    • Random Person

      I have the exact same question. Did you ever figure this out?

      • Daniel Branco

        Using the login selector itself instead the router-outlet and the router links?

        • Random Person

          That’s an interesting thought. Are you saying that on the index page (or wherever the router-outlet appears), use something like *ngIf on the router-outlet tag (or surrounding tag) to hide the router-outlet if the route is /login? If not then I’m not exactly sure how to replace the router-outlet with the login selector.

          • Daniel Branco

            You can always have a service with a BehaviorSubject that after login it is announce that a user is logged so your app.component.ts subscribe to that observable in the service and have a ngif controlling when the user is logged or not. When arriving home I can create a quick example

          • Random Person

            OK, that would be interesting to see. My layout is 2 columns, a sidebar and a main window. I have an authentication service that redirects the user to the /login route when their session times out or if they click logout. So I know when they are not logged in. I just want to show the login component for the entire screen instead of just the right side main window. In other words, I want the header and the sidebar to go away when not authenticated. That’s why I was thinking about ngIf.

          • Daniel Branco

            Sorry I just take a little time trying to find a place to share the example.

            https://stackblitz.com/edit/login-vs-routeroutlet

            Not sure if this is what you are looking for, I am beginning and I only have 1 week and a half training and learning.

            If you click in “login” it will remove the login component and display the router-outlet, if you click the logout it will remove the router-outlet and display the login component again

          • Random Person

            Thank you. I will take a look tomorrow. I have built a lot of software and have gone through Angular 4 training with some place called OLN but they were terrible. I didn’t get my money’s worth, at all. Sometimes the best teachers are others who are going through the same challenges!

          • Random Person

            OK, I had time to look at your example and you’ve essentially done what I thought earlier; used ngIf to hide parts of the layout when the user isn’t logged in. That’s perfectly acceptable. I’m sure there are is a way to have the router actually kick the user to an entirely different page (somehow?) – and it would be cool to know how to do that, too – but the ngIf solution works for now. Thanks for your example. (I was a little confused at first since the anchor tags aren’t generating the select cursor on mouseover. I thought it was because you used routerLink for your anchor tags but if you don’t, it causes a full postback. I’m curious how to make a link display the cursor without routerLInk….one thing after another with this platform!)

          • Random Person

            Ah, try this format for your links:
            a [routerLink]=”[‘world’]”>World Link Text Here…

            Pass in the routerLink params as an array of strings. The property binding makes sure the cursor now appears.

  • Anil Singh
  • leegee

    @view was removed around beta 13 — so presumably the rest of his document is out-of-date and irrelevant?

  • Alex Mills

    What is the provide() function? where is it coming from?

  • Karl Schipul

    “Angular’s router is super easy to use, and below I’ll share some of the basics.”

    https://uploads.disquscdn.com/images/40f738175656a08a202d6fde5e8d0e103cc2713e2739ac19f7fb56860d1b3d27.jpg