Angular Tutorial For Beginners - Part Nine - Routing

This is part 9 of the Angular tutorial for Beginners series.
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.
 
Angular Routing
 
Angular also imported AppRoutingModule in the app.module.ts for us,
 
Angular Routing
 
We will also find that a router-outlet has been added in the app.component.html.
 
Angular Routing
 
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.
 
Angular Routing
 
Let’s create two components to be used for our two pages as below:
  1. ng g c page1 
  2. ng g c page2
Now let’s add paths to our Routermodule routes as below,
  1. {path:'Page1', component:Page1Component},  
  2. {path:'Page2', component:Page2Component},  
And also import the component as below,
  1. import { Page1Component } from './page1/page1.component';  
  2. import { Page2Component } from './page2/page2.component';  
Angular Routing
 
Let’s add a nav section in the app.component.html section as below,
  1. <nav>  
  2.     <a routerLink="/Page1">Page1</a>  
  3.     <a routerLink="/Page2">Page2</a>  
  4.   </nav>  
Angular Routing
 
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.
 
Angular Routing
 
I will click on Page 1.
 
Notice how the URL changes and page 1 is displayed where we had written <router-outlet></router-outlet>
 
Angular Routing
 
The will work similarly for Page 2.
 
For more information on routing visit the official angular website.
 
This concludes the article about routing.
 
This article was originally published on my website taagung.


Similar Articles