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,
- {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
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
- <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
- <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent"
-
- aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
- <span class="navbar-toggler-icon"></span>
- </button>
- <div class="collapse navbar-collapse" id="navbarSupportedContent">
- <ul class="navbar-nav mr-auto">
- <li class="nav-item active">
- <a class="nav-link" href="#">Products
- <span class="sr-only">(current)</span>
- </a>
- </li>
- </ul>
- </div>
- </nav>
- <!-- End of NavBar and cards section -->
- <div class="container">
- <div class="row p-5">
- <div class="card-deck">
- <div class="col-4 pb-2" *ngFor="let prd of product;let i=index ">
- <div class="card ">
- <img [routerLink]="['/productdescription', i]" src="{{prd.productsrc}}" class="card-img-top">
- <div class="card-body">
- <h5 class="card-title">{{prd.productname}}</h5>
- <h6 class="text-success">₹ {{prd.productcost}}</h6>
- </div>
- </div>
- </div>
- </div>
- </div>
- </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:
- <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
- import { Component, OnInit } from '@angular/core';
- @Component({
- selector: 'app-navigation',
- templateUrl: './navigation.component.html',
- styleUrls: ['./navigation.component.css']
- })
- export class NavigationComponent implements OnInit {
- public product: any[];
- constructor() { }
- ngOnInit() {
- this.product = [{
- productname: 'nokia5.1,',
- productcost: '12000',
- productsrc: 'assets/images/nokia5.1.1.jpg',
- },
- ];
- }
- }
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,
- <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
- <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent"
-
- aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
- <span class="navbar-toggler-icon"></span>
- </button>
- <div class="collapse navbar-collapse" id="navbarSupportedContent">
- <ul class="navbar-nav mr-auto">
- <li class="nav-item active">
- <a class="nav-link" href="#">Products
- <span class="sr-only">(current)</span>
- </a>
- </li>
- </ul>
- </div>
- </nav>
- <!-- End of NavBar and cards section -->
- <div class="container">
- <div class="card-deck">
- <div class="card " *ngIf="prd != null">
- <div class="card-body">
- <div class="row">
- <div class="col-6">
- <img src="{{prd.productsrc}}" class="card-img-top" alt="Nokia">
- </div>
- <div class="col-6">
- <h3>Product Description</h3>
- <h5 class="card-title">{{prd.productname}}</h5>
- <h6>₹ {{prd.productcost}}</h6>
- <div>
-
- {{prd.productdescription }}
-
- </div>
- <div>
-
- {{prd.productdescription01}}
-
- </div>
- <br>
- <div class="label">
- <label for="quantity">
- <strong> Quantity</strong>
- </label>
- <input type="number" min="1" max="100" class="form-control" id="quantity">
- <br>
- <button type="button" class="btn btn-primary">Add to Cart</button>
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
After including the pieces of code now we need to include the following below code inside the product description. TS component file.
- import { Component, OnInit, AfterViewInit } from '@angular/core';
- import { ActivatedRoute } from '@angular/router';
- @Component({
- selector: 'app-productdescription',
- templateUrl: './productdescription.component.html',
- styleUrls: ['./productdescription.component.css']
- })
- export class ProductdescriptionComponent implements OnInit, AfterViewInit {
- ngAfterViewInit(): void {
- }
-
-
-
-
- public prd: any = null;
-
- public product: any [];
- constructor(
- public activatedRoute: ActivatedRoute
- ) { }
- ngOnInit() {
- this.product = [{
- productname: 'nokia5.1,',
- productdescription: '3000 mah',
- productdescription01: '4 GB RAM 64 GB Internal storage',
- productcost: '12000',
- productsrc: 'assets/images/nokia5.1.jpg',
- },
- ];
- this.activatedRoute.params.subscribe(param => {
-
- this. Prd = this.product[param['id']];
- });
- }
- }
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.
- import { NgModule } from '@angular/core';
- import { Routes, RouterModule } from '@angular/router';
- import { ProductdescriptionComponent } from './productdescription/productdescription.component';
- import { NavigationComponent } from './navigation/navigation.component';
- const routes: Routes = [{
- path: 'productdescription/:id',
- component: ProductdescriptionComponent
- }, {
- path: '',
- component: NavigationComponent
- }];
- @NgModule({
- imports: [RouterModule.forRoot(routes)],
- exports: [RouterModule]
- })
- export class AppRoutingModule { }
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
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.