Angular Routing

Quick Look – Angular Routing


| October 17, 2018 | in

One of the great things about Angular is that it provides everything pretty much out of the box. You don’t have to string together a bunch of tools, you can just focus on solving problems. In this blog post, we are going to focus on the Angular Router.

Since Angular is a single page application (SPA) framework, it has to provide some way to handle routing in the browser. This means that when switching between views, those switches need to occur entirely in the browser.

In non-SPA applications, page reloads (also known as switches) involve a full reload of the page. These are acceptable most of the time. But when you are building higher-end consumer applications or applications that include a lot of interactivity, those full-page reloads can become annoying to users. This is one of the advantages of SPAs.

Create an Angular Project

ng new AngularProject

From within the Angular project, create some components.

ng generate component ContactList
ng generate component ContactDetail
ng generate component EventList
ng generate component EventDetail

Setting up a router requires a few changes. First, we are going to configure our routes in the app.module.ts file. In this sample application, we will have four routes (one for each component we have created).

After we have our routes created, we need to add some links to our bootstrap navbar. We are going to do this in our app.component.html file. We are also going to add a router outlet to the bottom of that file.

At this point, we will be able to navigate to our Contacts and Events pages, but we won’t be able to navigate to our contacts or events details. This will require a little more code on our part.

Let’s stand up a sample contact list with some actual data. For this, we are just going to use a simple HTML table and an Angular click method.

We will have to modify the Contact Detail page to handle the click event and allow the user to navigate there. To accomplish this, we will use the navigate method on the Angular router.


Angular Routing

Getting going with Angular’s client-side routing is easy. You can have an SPA running with routing running in the browser with just a few steps.

Related posts