Navigate From One Component To Another Component Using Router

Overview of Routing in Angular and Implementation

 
In this article, I will explain about routing that is used in Angular and by using it, we can navigate from one component to another component. The routing allows the user to build single-page applications SPA’s with multiple views and allows you to navigate between them. An Angular router is a powerful tool that is developed by Google and maintained by the Angular team, and it is installed from the Angular router package. One more advantage used in routing is the usage of params in it. The Angular Router allows you to access parameters in different ways, by like,
  • Using activated router service,
  • Using the param map observable.
The user can also create a route parameter using the following mentioned syntax. This is an example route with an id parameter,
  1. {path: 'contacts/:id', component: ContactComponent}  

Implementation of Angular routing

 
Now I’m going to create a new Angular application using either CMD or using visual studio code (IDE).
 
After creating a new angular application by providing CSS and including router, the application is created.
 
In this article, I have designed a very simple basic simple online shopping program which would navigate from one component to another component,  and I have used bootstrap for including navbar and as well as using card deck. For using this kind of predefined library framework we need to install bootstrap, and for that I have used this command:
 
npm install bootstrap –save
 
After installing the bootstrap, we need to provide the referral link so that the page will be responsive to the usage of different kinds of devices. I have provided the path for bootstrap in index.html page for utilizing this.
 
Now this brings us to the creation of two components, the default parent component is created on the creation of a new Angular application, and we still need to create two child components so that we can exchange the data and navigate from one to another. Create components using these following commands, 
  • ng g c navigation
  • ng g c productdescription
 Navigate From One Component To Another Component Using Router
 
So after creating new two components we can add the following lines of code inside the child components, as I said I have used bootstrap for providing the responsive sites and selected navbar. As per my usage you can also use the desired navbar on this provided site. I have provided the link so that you can use the bootstrap. Now back to child component named navigation.html, use the code to copy and paste on navigation.html
  1. <nav class="navbar navbar-expand-lg navbar-dark bg-primary">  
  2.     <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent"  
  3.   
  4. aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">  
  5.         <span class="navbar-toggler-icon"></span>  
  6.     </button>  
  7.     <div class="collapse navbar-collapse" id="navbarSupportedContent">  
  8.         <ul class="navbar-nav mr-auto">  
  9.             <li class="nav-item active">  
  10.                 <a class="nav-link" href="#">Products   
  11.                     <span class="sr-only">(current)</span>  
  12.                 </a>  
  13.             </li>  
  14.         </ul>  
  15.     </div>  
  16. </nav>  
  17. <!-- End of NavBar and cards section -->  
  18. <div class="container">  
  19.     <div class="row p-5">  
  20.         <div class="card-deck">  
  21.             <div class="col-4 pb-2" *ngFor="let prd of product;let i=index ">  
  22.                 <div class="card ">  
  23.                     <img [routerLink]="['/productdescription', i]" src="{{prd.productsrc}}" class="card-img-top">  
  24.                         <div class="card-body">  
  25.                             <h5 class="card-title">{{prd.productname}}</h5>  
  26.                             <h6 class="text-success">₹ {{prd.productcost}}</h6>  
  27.                         </div>  
  28.                     </div>  
  29.                 </div>  
  30.             </div>  
  31.         </div>  
  32.     </div>  
In the code I have said if I click the image which is displayed inside the card deck the page should be navigated from one to another, and for that I have used the following command:
  1. <img [routerLink]="['/productdescription', i]" src="{{prd.productsrc}}" class="card-img-top" alt="Nokia">  
Now open the file navigation component.TS file and use the following code below as provided
  1. import { Component, OnInit } from '@angular/core';  
  2. @Component({  
  3.    selector: 'app-navigation',  
  4.    templateUrl: './navigation.component.html',  
  5.    styleUrls: ['./navigation.component.css']  
  6. })  
  7. export class NavigationComponent implements OnInit {  
  8.    public product: any[];  
  9.    constructor() { }  
  10.    ngOnInit() {  
  11.    this.product = [{  
  12.       productname: 'nokia5.1,',  
  13.       productcost: '12000',  
  14.       productsrc: 'assets/images/nokia5.1.1.jpg',  
  15.       },  
  16.     ];  
  17.   }  
  18. }  
So far I have used the code of creating navbar and card deck which is used to display the simple card which will contain the properties of the product and the cost of the mobile.
 
Now coming to the next step we need add the following code in another child component that we created along with the other component, now open the productdescription.html component and add the following code below,
  1. <nav class="navbar navbar-expand-lg navbar-dark bg-primary">  
  2.     <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent"  
  3.   
  4. aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">  
  5.         <span class="navbar-toggler-icon"></span>  
  6.     </button>  
  7.     <div class="collapse navbar-collapse" id="navbarSupportedContent">  
  8.         <ul class="navbar-nav mr-auto">  
  9.             <li class="nav-item active">  
  10.                 <a class="nav-link" href="#">Products   
  11.                     <span class="sr-only">(current)</span>  
  12.                 </a>  
  13.             </li>  
  14.         </ul>  
  15.     </div>  
  16. </nav>  
  17. <!-- End of NavBar and cards section -->  
  18. <div class="container">  
  19.     <div class="card-deck">  
  20.         <div class="card " *ngIf="prd != null">  
  21.             <div class="card-body">  
  22.                 <div class="row">  
  23.                     <div class="col-6">  
  24.                         <img src="{{prd.productsrc}}" class="card-img-top" alt="Nokia">  
  25.                         </div>  
  26.                         <div class="col-6">  
  27.                             <h3>Product Description</h3>  
  28.                             <h5 class="card-title">{{prd.productname}}</h5>  
  29.                             <h6>₹ {{prd.productcost}}</h6>  
  30.                             <div>  
  31.   
  32. {{prd.productdescription }}  
  33.   
  34. </div>  
  35.                             <div>  
  36.   
  37. {{prd.productdescription01}}  
  38.   
  39. </div>  
  40.                             <br>  
  41.                                 <div class="label">  
  42.                                     <label for="quantity">  
  43.                                         <strong> Quantity</strong>  
  44.                                     </label>  
  45.                                     <input type="number" min="1" max="100" class="form-control" id="quantity">  
  46.                                         <br>  
  47.                                             <button type="button" class="btn btn-primary">Add to Cart</button>  
  48.                                         </div>  
  49.                                     </div>  
  50.                                 </div>  
  51.                             </div>  
  52.                         </div>  
  53.                     </div>  
  54.                 </div>  
After including the pieces of code now we need to include the following below code inside the product description. TS component file.
  1. import { Component, OnInit, AfterViewInit } from '@angular/core';  
  2. import { ActivatedRoute } from '@angular/router';  
  3. @Component({  
  4.    selector: 'app-productdescription',  
  5.    templateUrl: './productdescription.component.html',  
  6.    styleUrls: ['./productdescription.component.css']  
  7. })  
  8. export class ProductdescriptionComponent implements OnInit, AfterViewInit {  
  9.    ngAfterViewInit(): void {  
  10. }  
  11. // tslint:disable-next-line: semicolon  
  12. // tslint:disable-next-line: member-ordering  
  13. // tslint:disable-next-line: semicolon  
  14. // tslint:disable-next-line: member-ordering  
  15. public prd: any = null;  
  16. // tslint:disable-next-line: member-ordering  
  17. public product: any [];  
  18. constructor(  
  19.    public activatedRoute: ActivatedRoute  
  20. ) { }  
  21. ngOnInit() {  
  22. this.product = [{  
  23.    productname: 'nokia5.1,',  
  24.    productdescription: '3000 mah',  
  25.    productdescription01: '4 GB RAM 64 GB Internal storage',  
  26.    productcost: '12000',  
  27.    productsrc: 'assets/images/nokia5.1.jpg',  
  28.    },  
  29. ];  
  30. this.activatedRoute.params.subscribe(param => {  
  31.    // tslint:disable-next-line: no-string-literal  
  32.    this. Prd = this.product[param['id']];  
  33.    });  
  34.   }  
  35. }  
Further after proceeding up to this point, we need to include the routing component in app-routing. module.ts and add the following code as I have given below and import the created components after adding the path in routes.
  1. import { NgModule } from '@angular/core';  
  2. import { Routes, RouterModule } from '@angular/router';  
  3. import { ProductdescriptionComponent } from './productdescription/productdescription.component';  
  4. import { NavigationComponent } from './navigation/navigation.component';  
  5. const routes: Routes = [{  
  6. path: 'productdescription/:id',  
  7. component: ProductdescriptionComponent  
  8. }, {  
  9.    path: '',  
  10.    component: NavigationComponent  
  11. }];  
  12. @NgModule({  
  13.    imports: [RouterModule.forRoot(routes)],  
  14.    exports: [RouterModule]  
  15. })  
  16. export class AppRoutingModule { }  
Navigate From One Component To Another Component Using Router
 
So we have created two child components and have imported the routing into app-routing-module.ts file and so, we can run the application by using the following command and view the output the browser.
 
ng s -o
 
Navigate From One Component To Another Component Using Router
 
Navigate From One Component To Another Component Using Router
 
As you can see, when I click the image in the card deck of the navigation component which is displayed, first it will navigate from one component to another component, named productdescription component. But from this article I didn’t use MVC type and this is not a good practice. And so in the next article I will use services to pass the data to the component so that the component can use the data which is coming from services.