Monday, August 3, 2020

Angular Routing Concepts With Example

While writing any application we split it into different areas, UI is no different and you will have different web pages for different functionalities that will be derived, relative to the current URL, as an action to the event like clicking a button or a link. In Angular it is done using Angular routing where router enables navigation detecting change in browser URL as an instruction to change the view.

In this post we’ll go through an Angular routing example to understand how to configure routing and to understand different concepts related to the router.

Client side routing

In client side routing you don’t necessarily go to the server to get a new page. In Angular apps which are known as Single Page Apps (SPA) server gives us a single page and you change what the user sees by showing or hiding portions of the display that correspond to particular components. Read more about client side routing in this post- What is Client Side Routing in Angular.

Building blocks of Angular routing

  1. Import RouterModule and Routes into your routing module. Using Routes you configure the routes for your application.
  2. <router-outlet> element is a placeholder to inform Angular where to put the content for the selected route.
  3. RouterLink directive is used to create a link to navigate to a route.

Angular routing example

With the help of this Angular routing example we’ll see how to configure routing paths. There is a menu as shown below and you have to show the corresponding component on click of the menu option.

Angular routing

1. Creating routing module

We’ll create a separate routing file app-routing.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { AccountComponent } from './account.component';
import { HomeComponent } from './home.component';
import { ServiceComponent } from './service.component';


const routes: Routes = [{path: '', redirectTo:'/home', pathMatch: 'full'},
                        {path: 'home', component: HomeComponent},
                        {path: 'account', component: AccountComponent},
                        {path: 'service', component: ServiceComponent}
                       ];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

In this RoutingModule class you can notice the following things for routing-

  1. Import RouterModule and Routes into your routing module.
    import { Routes, RouterModule } from '@angular/router';
    
  2. Configure your routes in a Routes array by specifying the path and the component they are mapped to.
    const routes: Routes = [{path: '', redirectTo:'/home', pathMatch: 'full'},
                            {path: 'home', component: HomeComponent},
                            {path: 'account', component: AccountComponent},
                            {path: 'service', component: ServiceComponent}
                           ];
    

    Each route in this array is a JavaScript object containing two properties-

    • First property, path, defines the URL path for the route.
    • The second property, component, defines the component Angular should use for the corresponding path.

    There is also a redirect setup where path: '' means to use the initial relative URL and it defaults to the home route.

  3. Configures the imports and exports arrays for @NgModule(). In the RouterModule.forRoot() method you pass the routes array. This method creates and configures an NgModule with all the router providers and directives.

2. Import the AppRoutingModule into AppModule (app.module.ts) and add it to the imports array.

import { AppRoutingModule } from './app-routing.module';
imports: [
  BrowserModule,
  AppRoutingModule
],

3. Adding the configured routes to the application.

Code for menu and adding link for routes is done in the app.component.html template itself for this example.

<nav class="navbar navbar-expand-md bg-dark navbar-dark">
  <div class="container-fluid">
    <div class="collapse navbar-collapse" id="collapsibleNavbar">
      <ul class="nav navbar-nav">
        <li class="nav-item" routerLinkActive="active"><a class="nav-link" routerLink="/home">Home</a></li>
        <li class="nav-item" routerLinkActive="active"><a class="nav-link" routerLink="/account">Accounts</a></li>
        <li class="nav-item" routerLinkActive="active"><a class="nav-link" routerLink="/service">Services</a></li>
      </ul>
    </div>
  </div>
</nav>
<div class="container">
  <div class="row"><p></p></div>
  <div class="row">
    <div class="col-md-12">
      <router-outlet></router-outlet>
    </div>
  </div>
</div>

For menu styling Bootstrap 4 is used in the template.

To create a link to navigate to a given route, routerLink is used in Angular routing application rather than href. If you use href then clicking a link results in a page reload and that’s something you don't want in your single page apps. Using RouterLink directive to create a link to route doesn't cause full page reload.

<a class="nav-link" routerLink="/account">Accounts</a>

Value given here for routerLink should be same as how route path is configured in routes array in routing module.

routerLinkActive="active" ensures that the currently selected menu option is highlighted. Bootstrap framework is used in the example which already provides this active class so you don’t need to write this CSS class yourself.

In your single page apps you don’t want a full page reload you just want to substitute the content with the content of the selected route’s component. To inform Angular where do we want to render the contents for the selected, we use the RouterOutlet directive.

Placement of <router-outlet></router-outlet> defines where content will be rendered.

Another way to define routerLink

There is one more way to define a routerLink using property binding. If used this way you can pass the path segments as array elements. For example, if you want to define route to service using routerLink with property binding.

<a class="nav-link" [routerLink]="['/service']">Services</a>

Creating components

We are done with the configuration for Angular routing now we’ll go through the mapped components. Here focus is on understanding routing so data is hardcoded in the components.

Home Component (home.component.ts)

import { OnInit, Component } from '@angular/core';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html'
})
export class HomeComponent implements OnInit {
  userId = 'UID0023';
  constructor() { }

  ngOnInit() {
  }
}

home.component.html

<h4>Welcome to XYZ Bank</h4>
<p>{{ userId }} logged in.</p>

Account Component (account.component.ts)

import { Component } from '@angular/core';

@Component({
  selector: 'app-account',
  templateUrl: './account.component.html'
})
export class AccountComponent {
  accounts = [
    {
      accountnumber: 1001,
      type: 'Saving'
    },
    {
      accountnumber: 1002,
      type: 'Checking'
    }
  ];
}

account.component.html

<div class= "row">
  <div class="col-xs-4 col-md-6">
  <h2>Account Details</h2>
  <table class="table table-sm table-bordered m-t-4">
    <tr>
      <th>Account Number</th>
      <th>Account Type</th>
    </tr>
    <tr *ngFor="let account of accounts">
      <td>{{account.accountnumber}}</td>
      <td>{{account.type}}</td>
    </tr>
  </table>
  </div>
</div>

Service Component (service.component.ts)

import { Component } from "@angular/core";

@Component({
  selector: 'app-service',
  templateUrl:'./service.component.html'
})
export class ServiceComponent{
  services = [
    'Deposit Money',
    'Open FD',
    'Mail Customer Care'
  ]; 
}

service.component.html

<h2>Services Offered</h2>
<div class="row">
  <div class="col-xs-12 col-sm-6">
    <div class="list-group">
      <a
        href="#"
        class="list-group-item"
        *ngFor="let service of services">
        {{ service }}
      </a>
    </div>
  </div>
</div>

Add these components in the declarations array of the AppModule.

Running the application

Once the application is successfully compiled and you access it using http://localhost:4200 that redirects to the http://localhost:4200/home. Clicking on Home menu option also displays the same component.

Angular routing example

Clicking on Account menu option


Same way clicking on Service menu option displays the Service component.

That's all for this topic Angular Routing Concepts With Example. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Angular Tutorial Page


Related Topics

  1. Path Redirection in Angular Routing
  2. Highlight Currently Selected Menu Item Angular Routing Example
  3. Setting Wild Card Route in Angular
  4. Using RouterLinkActiveOptions to Fix Link Highlighted Problem
  5. Passing Query Parameters in Angular Routing

You may also like-

  1. Angular Custom Two-Way Data Binding
  2. Angular @Input and @Output Example
  3. Angular - Call One Service From Another
  4. Creating New Component in Angular
  5. Pre-defined Functional Interfaces in Java
  6. Difference Between StackOverflowError and OutOfMemoryError in Java
  7. Writing a File Asynchronously Java Program
  8. Passing Arguments to getBean() Method in Spring

No comments:

Post a Comment