Angular 2 Router Example - lishman.io
lishman.io Loading..
Style: Blog or IDE

Angular 2 Router Example

Use the Angular 2 router to navigate between components when the user clicks a link. We take a look at routerLink, routerLinkActive, <router-outlet> and more.

Quick Tip

In the text below, when you see a word or phrase with this color, click on it to highlight the source code.

Also, take a look at the IDE style to see this tutorial in wide-screen mode. You can always switch back using the Style link at the top of the page.

Show me the IDE style

The Application

This is the simple demo application we will be using. We'll see how the router manages the contents of the colored area whenever a link is clicked. Go ahead, give it a try.

Loading...

The Menu

First let's take a look at our menu. The routerLink directive on the anchor element is bound to a string containing the path of a route. We see how the router handles these paths in the next section.

We also include a <router-outlet> element in the template. This is where the content is rendered by the router when a particular route is selected. So when the user clicks one of the links, or types the path in the address bar (e.g. http://example.com#/green), the router will output the appropriate content in <router-outlet>.

Also, routerLinkActive adds the CSS class in quotes to the anchor element when the route is active, effectively disabling the link.

app.component.ts x
Loading...

Routes

Next we configure the router to handle the red, green and blue paths that we specified in the routerLink directives in our menu.

To do this, we build an array of objects which map our paths to a particular component. We include a redirectTo entry which provides a default route by redirecting to /green when the path is empty.

This array is then passed into the forRoot method of RouterModule. The return value from this method is exported so that we can include it in our module.

app.routes.ts x
Loading...

NgModule

Our route definitions are added to the module by including the routing variable in the imports property of the @NgModule directive.

HashLocationStrategy is a LocationStrategy which tells Angular to represent its state in the hash fragment of the browser's URL, for example http://example.com#/red. This overrides the default of PathLocationStrategy which produces a URL like this: http://example.com/red.

app.module.ts x
Loading...

Summary

So when the user clicks one of the links in the menu, the router will map the path to a component, and render the view in <router-outlet>. When a route is active, routerLinkActive disables the link by adding the disabled class to the element.

app.component.ts x
Loading...

Where Next?

More Tutorials

To find out how to use child routes, see this Angular 2 Child Routes tutorial.

Source Code

The source code for this tutorial is available in the angular-2-router GitHub repo.