Angular Routing Example

angular routing tutorial

So far we only have one view in our little Angular application. Of course we are going to want to have more options for the user to visit different views for different information and experiences. Just like we have links on basic web pages, we can also set up links in an Angular application to navigate to various views. It is via the routing functionality provided in Angular that we can set up various routes to various sets of information. In this tutorial, we’ll learn about how routing works, how to configure routes, how to link routes to actions, and how to build the various views we’ll need.


Creating A New Component

Right now, there is a simple game list component that shows a list of all the games in the application. Now, we want to build a new component which shows the details of one game at a time. We will want to be able to click on a link, and have the Angular routing work so that we are sent to a detailed view of that game. In other words, we need a new component so that we can route to that component. Here is what the game detail component will look like.
angular game detail component

The game detail component consists of game-detail.css, game-detail.component.html, and game-detail.component.ts. They live in the games folder. Here are those files.


game-detail.css


game-detail.component.html


game-detail.component.ts


How Angular Routing Works

All views are displayed within one page in an Angular Application. This is what’s known as a Single Page Application, or SPA. The page where all the views are displayed is typically the index.html file. Ours looks like this.

Any number of pages, or views, can be displayed on the index page at any given time. You may have three views, or you could have hundreds. Any one of them could be set up to be displayed in the index.html file. How does this happen? This happens using Routing In Angular. To set up routing in Angular you can take these steps.

  • Configure a route for each component
  • Define the options or actions for the user
  • Link a route to an option or action
  • Trigger the route based on user action (clicks)
  • When a route is activated, the component view is displayed

In the screenshot below is a sample menu which provides the options to a user of the application. A route is tied to the menu option (the links) so that Angular can route to a certain component. This is accomplished with the built-in router directive of routerLink. When the user clicks on the Games option, and Angular router navigates to the /games route. This updates the browser URL and loads the desired component into the view.
routerlink in angular

Therefore, when the user visits http://localhost:4200/games in the address bar, they see the list of games.
angular menu navigation


Configure Routes

Let’s see how to actually configure some routes in Angular. Routing is component based, and therefore the workflow is to first determine which component(s) you would like to have as a routing target. Then, you can define the route(s) as needed. First, we’ll need a HomepageComponent as this will now be displayed by default instead of the games list. This component lives in a home folder and consists of homepage.component.html and homepage.component.ts.


homepage.component.html


homepage.component.ts

In the app.module.ts file, we can now specify this component as the default route so to speak using RouterModule.forRoot().

It is in the app.component.ts file where we can set up the routerLink options for the user. In fact, we’ll use the routerLinkActive directive so that when a user navigates to a specific route, that button or link appears as highlighted. Also note the use of the special router-outlet element which is a placeholder that Angular dynamically fills based on the current router state. In other words, whenever a route is activated – the view associated with that route is loaded into the <router-outlet></router-outlet> tag for display.


Passing Parameters To A Route

In order to route to specific items of a collection, you can pass parameters to a route. For example, all of the games in our application have an id associated with them. In order to route to a specific game, we would need to somehow specify the id of the game in the route. For example visiting the http://localhost:4200/games/5 route shows a specific game.
angular route parameter example


game-list.component.html

In our game list component where we list out all of the games, we can set up route parameter passing as seen with the highlighted code below.


Define Routes With Parameters

Ok the links are in place noted above using the link in the format of <a [routerLink]=”[‘/games’, game.gameId]”>. Note the route is /games and after the comma we pass the id of the game we want to view. In order for this to work, the routes need to be defined somewhere in the application. For these links, we can define the routes in the game.module.ts file using RouterModule.forChild().

The game-detail.component.ts file must also be made aware of the route. To display the correct game, the game detail component reads the parameter from the url. Then, that parameter is used to fetch the correct game from the back-end API we had set up in an earlier tutorial. To get the parameter from the URL, the ActivatedRoute service is used. This is set up as a dependency in the constructor.

Testing the game detail routes in the browser is working quite well!


Activating Routes With Code

You may have noticed the Back button which takes us back to the game list component view. This route is activated using a dedicated function and is provided by the Router service. Here we get the game-detail.component.ts file ready for this type of routing.

Now in the game-detail.component.html file we can simply call the onBack() when the user clicks to trigger the routing navigation code.


Protect A Route With Guards

Different users of the application may have different levels of permissions. Perhaps only registered users should be able to visit a specific route. In a case like this, you can use guards in angular to protect a given route. The angular router provides these guards for you. They include the following options.

  • CanActivate – guard navigation to a route
  • CanDeactivate – guard navigation from a route
  • Resolve – Pre-fetch data before route activation
  • CanLoad – Prevents async routing

For our purposes, we can build a guard that will only allow a user to view the game detail component if a valid route parameter is provided in the URL. We can start with game.module.ts like so.

In the snippet above we are saying that, before a user can navigate to the game detail component, the GameDetailGuard must allow access. Now, we’ll need to create the guard itself and it shall have the rules needed. We will enforce that the id can not be 0 or NaN. Here is the game-detail.guard.ts. The logic we are interested in is highlighted, while the other code is standard angular boilerplate.


Angular Routing Example Summary

Passing Parameters
Any number of parameters can be passed to a route in angular, separated by slashes. For example, here is a route definition.

The parameter can be passed by populating the link parameters array bound to the routerLink directive.

In the component file, you can read the parameter value using the ActivatedRoute service.

Routing With Code
To activate a route with code, be sure to follow these steps.

  • Use the router service
  • Be sure to import the service and define it a dependency on the constructor
  • Add a method that calls the navigate method of the Router Service instance
  • Pass in the link parameters array
  • Add a user interface element
  • Leverage event binding to bind to the created method
  • Protect A Route With A Guard
    Prevent or allow access as you see fit using the Guard function provided by angular. To set up a guard, follow these steps.

  • Build a guard service
  • Implement the guard type (CanActivate, CanDeactivate, Resolve, or CanLoad)
  • Create the method needed (one of the above)
  • Register the guard service provider (providedIn)
  • Add the guard to the desired route
  • In this tutorial we had a look at some various routing techniques available in Angular. The basic concepts we should now be familiar with are how to pass parameters to a route in angular, how to activate a route with code, and how to protect a route with a guard. Routing is a complicated topic in Angular and there are many more things to learn such as required, optional, and query parameters, route resolvers, secondary router outlets, and lazy loading.