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="/">
Define the routes
const appRoutes={ path: 'product', component: ProductComponent }
Register the Routes
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
<li><a [routerLink]="['product']">Product</a></li>
Choose where you want to display
<router-outlet></router-outlet>
Example of Angular Router
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.
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>
Routes
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 } ];
{ path: 'home', component: HomeComponent },
{ path: 'contact', component: ContactComponent }, { path: 'product', component: ProductComponent },
Default Route
{ path: '', redirectTo: 'home', pathMatch: 'full' },
Wild Card Route
{ path: '**', component: ErrorComponent }
It's all about the order: the first one wins.
Register the Routes
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) ],
Defining The Navigation
<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>
Display the component using Router-outlet
<router-outlet></router-outlet>