Routing In Angular

Routing In Angular

In this Angular Routing article, we will learn how the Angular Router handles navigation and routing in Angular. We'll cover what Angular Routing is and how it works in this article. We will also take a look at the different parts that make up the Angular Router Module. Following that, we will go over how to set up and configure the router. Finally, we'll develop an Angular Routing Example application with four components and use the Angular Router to create a menu navigation system.

What is Routing?

Routing allows you to transition from one section of the application to another, or from one View to another.

The Angular Router Module

In Angular, the Router is a distinct module. @angular/router is its own library package. For browsing across application views, the Router Module offers the necessary service providers and directives.

You may use Angular Router to

  • Type a URL in the address bar to go to a certain view.
  • Optional parameters can be passed to the View.
  • When the user executes application operations, bind the clickable components to the View and load the view.
  • Handles the browser's back and forward buttons.
  • Allows you to load the view dynamically.
  • Guards protect the pathways from unauthorized users.

Components of Angular Router Module

Router

An Angular Router is an object that allows users to navigate from one component to the next while doing application operations like clicking on menus, links, buttons, or the browser's back/forward button. To browse to a route, we can access the router object and use its methods such as navigate() and navigateByUrl().

Route

When a user clicks a link or pastes a URL into the browser address bar, Route instructs the Angular Router on which view to display. Every Route has a path and a component to which it is mapped. Using the Route object, the Router object parses and constructs the final URL.

Routes

Our application provides an array of Route objects called Routes.

RouterOutlet

The outerOutlet (<router-outlet>) is a directive that serves as a placeholder for the Router to display the view.

RouterLink

The RouterLink directive associates an HTML element with a Route. The Route will be navigated if you click on the HTML element that is tied to a RouterLink. The RouterLink could have parameters that are provided to the route's component.

RouterLinkActive

RouterLinkActive is a directive that allows you to add or remove classes from a RouterLink bound HTML element. We may use this directive to change the CSS classes for active RouterLinks depending on the RouterState.

ActivatedRoute

The ActivatedRoute is a class that represents the presently active route for the loaded Component.

RouterState

The router's current state includes a tree of the presently active routes as well as convenience methods for traversing the tree.

RouteLink Parameters array

The Route's parameters or arguments. It's an array that you may bind to the RouterLink directive or send to the Router.navigate method as an argument.

How to configure Angular Router

You must follow these steps to configure the Router in Angular.

  • Set the <base href>
  • Define the view's routes.
  • Routes Map must be used to register the Router Service. Route HTML Element actions
  • Choose where you want the view to appear.

Set the <base href>

The base URL for all relative URLs within a page is specified by the HTML base> element.

The HTML5 style of routing (or PathLocationStrategy) is the default option for the Angular Router. For navigation and URL interaction, the router takes advantage of the browser's history API.

<base href="/">

We need to put up the "base href" in the DOM to make HTML5 routing work. This is done right after the head tag in the app's index.html file.

Define the routes

Create an array of route objects after that. Each route associates a component with a path (URL Segment).

const appRoutes={ path: 'product', component: ProductComponent }

path: The route's URL path section. This value will be used to refer to this route across the app.

component: This is the component that will be loaded.

When a user visits the URL "/product," this route instructs Angular to render ProductComponent.

Register the Routes

Import the Router Module from the @angular/router library into the application's root module.

import { RouterModule } from '@angular/router';

Then use the RouterModule.forRoot method to install the routes, passing the routes as an argument in the imports array.

imports: [RouterModule.forRoot(routes)],

Map Action to Routes

After that, we must connect the link, picture, or button's click event to a route. The routerLink directive is used to do this.

<li><a [routerLink]="['product']">Product</a></li>

Route names and parameters are accepted by the routerLink directive. The Link Parameters array is the name of this array.

The router searches in the routes array and activates the instance of the component associated with the route "product," which is ProductComponent, when the application requests navigation to the route "product." The browser's address and history have likewise been changed to /product.

Choose where you want to display

Finally, we must tell angular where the view should be displayed. As seen, the RouterOutlet directive is used to do this. The following directive will be added to the root component.

<router-outlet></router-outlet>

Example of Angular Router

Let's create a prototype application with four components and a navigation system to route them all.

The Welcome message will be displayed by the HomeComponent. This is also the component that we use by default.

HomeComponent: The Welcome message will be displayed in this component. This is also the component that we use by default.

import {Component} from '@angular/core';
 
@Component({
    template: `<h1>Welcome!</h1>
              <p>This is Home Component </p>
             `
})
 
export class HomeComponent {
}

ContactComponent: The contact message is displayed.

import {Component} from '@angular/core';
 
@Component({
     template: `<h1>Contact Us</h1>
                <p>TekarticlesHub </p>
                `
})
export class ContactComponent {
}

ProductComponent: The product list is displayed. Dependency injection is used to retrieve the Products from the Angular 2 Service.

The code of the product.component.ts file:

import { Component, OnInit } from '@angular/core';
 
import { ProductService } from './product.service';
import { Product } from './product';
 
@Component({
  templateUrl: './product.component.html',
})
 
export class ProductComponent
{
 
   products:Product[];
   
   constructor(private productService:ProductService){
   }
 
   ngOnInit() {
     this.products=this.productService.getProducts();
   }
  
}

The code of the product.component.html file:

<h1>Product List</h1>
<div class='table-responsive'>
    <table class='table'>
        <thead>
            <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Price</th>
            </tr>
        </thead>
        <tbody>
            <tr *ngFor="let product of products;">
                <td>{{product.productID}}</td>
                <td><a [routerLink]="['detail',product.productID]">{{product.name}} </a> </td>
                <td>{{product.price}}</td>
            </tr>
        </tbody>
    </table>
</div>
 
<router-outlet></router-outlet>

ErrorComponent: When the user navigates to a path that does not exist, the ErrorComponent is displayed. This is essentially a 404 page.

import {Component} from '@angular/core';
 
@Component({
    template: `<h1>Page not found</h1>
               <p>This is a Error Page</p>
              `
})
 
export class ErrorComponent {
}

Product Service

import { Observable } from 'rxjs/Observable';
import {Product} from './Product'
 
 
export class ProductService{
 
    public getProducts() {
 
        let products:Product[];
 
        products=[
            new Product(1,'Memory Card',500),
            new Product(2,'Pen Drive',750),
            new Product(3,'Power Bank',100)
        ]
 
        return products;               
    }
 
 
    public getProduct(id) {
        let products:Product[]=this.getProducts();
        return products.find(p => p.productID==id);
    }
 
 
}

export class Product { 
 
    constructor(productID:number,    name: string ,   price:number) {
        this.productID=productID;
        this.name=name;
        this.price=price;
    }
 
    productID:number ;
    name: string ;
    price:number;
 
}

The code of the Index.html

<!doctype html>
<html>
<head>
  <base href="/">
  <meta charset="utf-8">
  <title>Angular 2 Routing</title>
 
 
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    ...
</head>
<body>
  <app-root>Loading...</app-root>
</body>
</html>

Note the <base href=”/”> right after the head tag. This makes the browser know where is the root of our application is and helps it to construct the URLs

Routes

We now have all of our components in place. The following step is to design our routes.

Creating all of our route configurations in a separate file is a good idea. As a result, place app.routes.ts in the app folder.

import { Routes } from '@angular/router';
 
import { HomeComponent} from './home.component'
import { ContactComponent} from './contact.component'
import { ProductComponent} from './product.component'
import { ErrorComponent} from './error.component'
 
export const appRoutes: Routes = [
  { path: 'home', component: HomeComponent },
  { path: 'contact', component: ContactComponent },
  { path: 'product', component: ProductComponent },
  { path: '', redirectTo: 'home', pathMatch: 'full' },
  { path: '**', component: ErrorComponent }
];

We begin by importing Routes from the router module.

Following that, we must import all of the components, which necessitates routing. Home, Contact, Product, and Error Components have all been imported.

Finally, we've created a constant (appRoutes) that holds the Routes we want to construct. Routes is a collection of route configuration objects (or route object).

Each route has a number of settings that can be changed.

The first path we will take is

{ path: 'home', component: HomeComponent },

The route, which represents the URL path segment, is the first parameter. The component to be displayed is the second parameter. The HomeComponent is displayed when you navigate to /home (URL path segment) with the above route setup.

It's worth noting that the path lacks the leading slash.

The next two paths are very similar to the one you took before.

{ path: 'contact', component: ContactComponent },
{ path: 'product', component: ProductComponent },

Default Route

The fourth option is to

{ path: '', redirectTo: 'home', pathMatch: 'full' },

The default route is indicated by the absence of a path. Using the RedirectTo parameter, the default route is redirected to the home path. When you navigate to the root of your application, /, you will be redirected to the home path (/home), which will display the HomeComponent.

It's worth noting that the pathMatch argument is set to 'full'. The pathMatch parameter instructs the Router on how to match the URL.

The path is matched to the complete URL when it is set to full.

For example, /contact/" terminates in an empty space. The router will apply the redirect if pathMatch is not set to full, resulting in the error.

Wild Card Route

The following route is the wildcard route.

{ path: '**', component: ErrorComponent }

Every URL is matched by the "**." The ErrorComponent will be displayed by the Router.

It's all about the order: the first one wins.

It's worth noting that the route's sequence is crucial. The Routes are matched in the order in which they were created. The Router always returns the first route that matches the criteria (first-match-wins strategy)

Because the wildcard route (**) matches all URLs, it should come last.

We've now established our routes. We'll now incorporate these routes into our application.

Register the Routes

Routes are registered in the application's root module. For example, app.module.ts:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
 
import { RouterModule } from '@angular/router';
 
import { AppComponent } from './app.component';
import { HomeComponent} from './home.component'
import { ContactComponent} from './contact.component'
import { ProductComponent} from './product.component'
import { ErrorComponent} from './error.component'
 
import { ProductService } from './product.service';
 
import { appRoutes } from './app.routes';
 
@NgModule({
  declarations: [
    AppComponent,HomeComponent,ContactComponent,ProductComponent,ErrorComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    RouterModule.forRoot(appRoutes)                           /*path location strategy */
    /*RouterModule.forRoot(appRoutes, { useHash: true }) */   /*Hashlocationstrategy */
  ],
  providers: [ProductService],
  bootstrap: [AppComponent]
})
export class AppModule { }

We begin by importing the RouterModule.

import { RouterModule } from '@angular/router';

Import all of the components after that.

import { AppComponent } from './app.component';
import { HomeComponent} from './home.component'
import { ContactComponent} from './contact.component'
import { ProductComponent} from './product.component'
import { ErrorComponent} from './error.component'

After that, import the routes that we set in the app.routes.

import { routes } from './app.routes';

Finally, we import the RouterModule, passing the routes we set via the forRoot method to it.

imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    RouterModule.forRoot(routes)
],

It's worth noting that we're employing the forRoot technique.

When you wish to provide a service while also configuring it, you use the forRoot method.

The routermodule.forroot method registers the Router Service and returns the Router Service configured with the routes supplied in the parameter. It also registers the other providers that are required by the routing module.

The Router service looks at the current browser URL and performs the initial navigation when the application is bootstrapped.

When a user changes the URL by clicking on a link on the page or typing it into the address bar, the router searches the Routes array for a related Route and renders the associated component.

Defining The Navigation

The navigation must then be defined.

Open the app.component.html file in your browser. Only navigation is handled by the AppComponent. It will show the menu choice, which the user can select to get to a specific view.

<div class="container">
 
<nav class="navbar navbar-default">
  <div class="container-fluid">
    <div class="navbar-header">
      <a class="navbar-brand" [routerLink]="['/']"><strong> {{title}} </strong></a>
    </div>
    <ul class="nav navbar-nav">
        <li><a [routerLink]="['home']">Home</a></li>
        <li><a [routerLink]="['product']">Product</a></li>
        <li><a [routerLink]="['contact']">Contact us</a></li>
    </ul>
  </div>
</nav>
 
 <router-outlet></router-outlet>
 
</div>

Our component is styled with Bootstrap.

<li><a [routerLink]="['home']">Home</a></li>
<li><a [routerLink]="['product']">Product</a></li>
<li><a [routerLink]="['contact']">Contact us</a></li>

To tie anchor tag components to the route, we use the routerLink directive.

RouterLink is a directive with an attribute. We put a square bracket around it. After that, the routerLink is bound to a template expression, which outputs an array of link parameters.

The parameters or arguments to the Route are stored in the Link Parameters array. The URL is created by the Angular Router module using the link parameters array.

The Router service uses the path to locate the route associated with the path and activates the component when the user clicks on the link.

Display the component using Router-outlet

Finally, we must tell Angular where the Component should be displayed. The Router-outlet directive is used to do this.

The RouterOutlet is a directive that informs Angular where we want the view to appear on our page.
The RouterOutlet and RouterLink directives do not need to be imported. When we imported RouterModule into our app, these directives were also imported. module.

<router-outlet></router-outlet>

Now, run the application using ng serve. When you type http://localhost:4200 in the address bar, you should see the HomeComponent, which is the default root, shown.

When you enter an invalid URL, the ErrorComponent should appear.

Click on the menu selections or use the browser's Back and Forward buttons. Everything should function as expected.

Conclusion

In this article, By creating a sample application, we learned what is an angular router and how to use it.

I hope this article helps you and you will like it.👍

If you have any doubt or confusion then free to ask in the comment section.

Post a Comment

Previous Post Next Post