Routing In Angular V4 And Above

Hi Readers, I hope you all are doing well. Please read my previous article, Angular Services For Sharing Data Between Components, in which I have explained the method by which we can share the required data between components using Angular services which is very important for Angular. Today, I am here with one more article, which is Angular Routing.

Now, two things which you should keep in your mind - What is Routing and why we are using it in Angular. I have already explained about routing in my previous article, and here, I am going to explain in more detail. 

What is Routing?

You can say simply: Angular provides a Router to make it easier to define routes for the web applications and to navigate from one view to another. The basic concepts behind routing are when a user needs to view any page based on specific URL, Angular provides a routing feature by which the view will be rendered of the specific component according to defined routing. 

Why Routing

We are using routing to navigate from one view to another. It's a basic need of all the web applications to move one page to another and show the required data within the view without loading full page. So, in this case, routing comes into the picture. With the help of routing, we can simply move multiple pages with any specified URL which one we need.

There are few steps which we have to do for Angular Routing. First, we will create the required component which is necessary to start the application. For component creation, you can use either command ng g component <componentname> or by the application which I had already explained in my previous tutorial so we will create 2 component as Home and Contact with HTML file for the initial step of routing as,

Step1

app.home.component.ts
  1. import { Component, OnInit } from '@angular/core';  
  2.   
  3. @Component({  
  4.     selector: 'app-root',  
  5.    templateUrl: 'app.home.component.html',   
  6. })  
  7. export class HomeComponent {  
  8.     
  9.     constructor() {          
  10.     }  
  11. }  

app.home.component.html

  1. <hr>  
  2. <div style="text-align:center">  
  3.     <div>  
  4.         <h1>Home Component</h1>         
  5.     </div>    
  6.     <hr>  

app.contact.component.ts

  1. import { Component, OnInit } from '@angular/core';  
  2.   
  3. @Component({  
  4.   selector: 'contact',  
  5.   templateUrl: 'app.contact.component.html',  
  6.     
  7. })  
  8. export class ContactComponent {  
  9.   public data;  
  10.     
  11.   constructor() {  
  12.      
  13.   }  
  14. }  

app.contact.component.html

  1. <hr>  
  2. <div style="text-align:center">  
  3.    <h1>Contact  component</h1>\  
  4.     
  5. </div>  
  6. <hr>  

Step 2

Now, we will create the routing file as,

app.routing.ts

  1. import { ModuleWithProviders } from '@angular/core';  
  2. import { Routes, RouterModule } from '@angular/router';  
  3. import { HomeComponent } from './app.home.component';  
  4. import { ContactComponent } from './app.contact.component';  
  5.   
  6. const appRoutes: Routes = [  
  7.     { path: '', redirectTo: 'home',pathMatch: 'full' },  
  8.     { path: 'home', component: HomeComponent },  
  9.     { path: 'contact', component: ContactComponent },  
  10.       
  11. ];  
  12.   
  13. export const routing: ModuleWithProviders =  
  14.     RouterModule.forRoot(appRoutes);  

As you can see above we have added routing file with required routing according to our component. Here, you need to know a few things about routing which we have added above:

Routes

Routes is an array of route configurations. Each one has the following properties:
type Routes = Route[];

We can import the Routes from @angular.router  that we are using in our application with a component that describes the routes we want to use. As you can see in above within the Routes we have defined the path which match the URL and component which will get the HTML page of the component.

Routes has few properties which we are using with routing. Here, I am going to explain few things which are required for the application:
  • path: is a string that uses the route matcher URL.
  • pathMatch: is a string that specifies the matching strategy as full.
  • component: is a component type.
  • redirectTo: is the URL fragment which will replace the current matched segment.

ModuleWithProvider

As you can see above, we can import the ModuleWithProvider from @angular/core which we are using with RouterModule which we can import from @angular.router. RouterModule has the method forRoot in which we can pass the Routes which we have created for routing.

Step 3

Now, we will create the navigation menu by which we can use the routing. In the navigation menu, we will add the component where we have added  <router-outlet></router-outlet>  as in the main component.

app.component.ts 

  1. import { Component, OnInit } from '@angular/core';  
  2.   
  3. @Component({  
  4.   selector: 'app-root',  
  5.   templateUrl: 'app.component.html',  
  6.     
  7. })  
  8. export class AppComponent {  
  9.     
  10.   public title: string = 'Routing example';  
  11.   
  12.   constructor() {  
  13.   
  14.   }  
  15. }  

app.component.html

  1. <div style="text-align:center">  
  2.     
  3.   <div>  
  4. <!-- navigation menu -->  
  5.     <nav>   
  6.       <ul>  
  7.         <li><a [routerLink]="['home']" [routerLinkActive]="['active']">Home</a></li>  
  8.   
  9.         <li><a [routerLink]="['contact']" [routerLinkActive]="['active']">Contact</a></li>  
  10.       </ul>  
  11.     </nav>  
  12.     <div>  
  13.         <h1>  
  14.           {{title}}  
  15.         </h1>  
  16.         <img width="100" height="100" alt="Angular Logo" src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNTAgMjUwIj4KICAgIDxwYXRoIGZpbGw9IiNERDAwMzEiIGQ9Ik0xMjUgMzBMMzEuOSA2My4ybDE0LjIgMTIzLjFMMTI1IDIzMGw3OC45LTQzLjcgMTQuMi0xMjMuMXoiIC8+CiAgICA8cGF0aCBmaWxsPSIjQzMwMDJGIiBkPSJNMTI1IDMwdjIyLjItLjFWMjMwbDc4LjktNDMuNyAxNC4yLTEyMy4xTDEyNSAzMHoiIC8+CiAgICA8cGF0aCAgZmlsbD0iI0ZGRkZGRiIgZD0iTTEyNSA1Mi4xTDY2LjggMTgyLjZoMjEuN2wxMS43LTI5LjJoNDkuNGwxMS43IDI5LjJIMTgzTDEyNSA1Mi4xem0xNyA4My4zaC0zNGwxNy00MC45IDE3IDQwLjl6IiAvPgogIDwvc3ZnPg==">  
  17.       </div>  
  18.       
  19.     <router-outlet></router-outlet>  
  20.   </div>  

As you can see above, we have added [routerLink] and <router-outlet></router-outlet> with the app.component.html file which is our main component file. Here, we are using [routeLink] with anchor for moving from one view to another view according to a specified route which we have added in app.routing.ts and <router-outlet></router-outlet> for rendering the view according to the component file.

Step 4

Now, we have to register each component and routing in the app.module.ts file as below,

app.module.ts

  1. import { BrowserModule } from '@angular/platform-browser';  
  2. import { NgModule } from '@angular/core';  
  3. import { AppComponent } from './app.component';  
  4. import { HomeComponent } from './app.home.component';  
  5. import { ContactComponent } from './app.contact.component';  
  6. import { routing } from './app.routing';  
  7.   
  8. @NgModule({  
  9.   declarations: [  
  10.     AppComponent, HomeComponent, ContactComponent,  
  11.   ],  
  12.   imports: [  
  13.     BrowserModule, routing  
  14.   ],    
  15.   bootstrap: [AppComponent]  
  16. })  
  17. export class AppModule { }  

As you can see above we have added the component in the declaration section and routing in imports section where we are using all the modules which is required for our application.

If you want to use some styles for the menu, you can use css within style.css which is global style sheet:

styles.css

  1. ul {  
  2.   list-style-type: none;  
  3.   margin: 0;  
  4.   padding: 0;  
  5.   overflow: hidden;  
  6.   background-color: #bda4a4;  
  7. }  
  8.   
  9. li {  
  10.   float: left;  
  11. }  
  12.   
  13. li a {  
  14.   display: block;  
  15.   color: white;  
  16.   text-align: center;  
  17.   padding: 14px 16px;  
  18.   text-decoration: none;  
  19. }  
  20.   
  21. li a:hover:not(.active) {  
  22.   background-color: #A09FB1;  
  23. }  
  24.   
  25. .active {  
  26.   background-color: #6AD4AC;  
  27. }  

Now, if everything is completed above, you can run the application using two steps,

Step 1

Open the node js command window and move to the location where you have added the application .

Step 2

Execute the command ng serve,

When application runs successfully, the below output should show,

Output for Home

Output for Home

Output for Contact

Output for Contact

So, these are the main steps which we have to use for routing in Angular. You can also download the application by zip file which I have shared with this article. You need to know one thing, after downloading the application first add it in any location and then run npm install. When npm install run successfully then you can run the application by ng serve command.

Conclusion

As you can see now the Angular Routing is the main feature of Angular which we are using in almost all the applications for moving from one page to another page without loading the page. I hope you liked this -- please share it if you did.


Similar Articles