Angular Tutorial

Angular Tutorial for Beginners Part 9: Routing

Tuba Mansoor
Latest posts by Tuba Mansoor (see all)

This is part 9 of the Angular tutorial for Beginners series.

Part 1 of this series discussed how to get started with Angular.

Part 2 discussed about the basic tenets of Angular Modules, Components and Directives.

Part 3 discussed data binding.

Part 4 discussed interfaces

Part 5 discussed how we can use services in angular.

Part 6 discussed Observables & Http requests.

Part 7 discussed how we can transform our output data with pipes.

Part 8 discussed how we can create nested components in Angular.

Let’s learn about routing in Part 9 of the Angular tutorial for Beginner series.

Initially when we created our project, Angular asked if we wanted to add routing. We said yes. Angular then created the app-routing.module.ts for us. It imported the RouterModule from @angular/router. This exposes the routing service and we can use routing directives. It also exposes the configured routes. We have also called the routing module for the root method. We later pass our routes here at the root level.

See also  Angular Tutorial for Beginners – Part 4 : Interfaces

Angular also imported AppRoutingModule in the app.module.ts for us

We will also find that a router-outlet has been added in the app.component.html.

These are the changes that angular made for us when we asked it to add to routing. Now let’s have a look at how we can use them.

Let’s create two components to be used for our two pages as below:

ng g c page1
ng g c page2

Now let’s add paths to our Routermodule routes as below:

 {path:'Page1', component:Page1Component},
 {path:'Page2', component:Page2Component},

And also import the component as below:

import { Page1Component } from './page1/page1.component';
import { Page2Component } from './page2/page2.component';

Let’s add a nav section in the app.component.html section as below:

<nav>
    <a routerLink="/Page1">Page1</a>
    <a routerLink="/Page2">Page2</a>
  </nav>

That’s all you need to do to implement routing in Angular. I will also comment out the rest of the code in the app.component.html and just keep the routing related code. Let’s open our application and have a look.

I can see it as below.

I will click on Page 1.

Notice how the url changes and page 1 is displayed where we had written <router-outlet></router-outlet>

The will work similarly for Page 2.

For more information on routing visit the official angular website.

This concludes the article about routing in angular.

Contents of the Angular tutorial for Beginners series:

See also  All About Method Overloading in C#

Part 1: Getting Started

Part 2: Modules, Components & Directives in Angular.

Part 3: Data binding in angular.

Part 4 : Interfaces

Part 5: Services in Angular

Part 6: Http Requests with Observables.

Part 7: Pipes in Angular

Part 8 :Nesting Components in Angular