Angular 6 Routing Example

The Angular CLI is a command line interface tool that can create a project, add files, and perform a variety of ongoing development tasks such as testing, bundling, and deployment. Angular 6 Routing Example, will help you to understand how the routing mechanism works. We use Angular 6 CLI to install Angular. After that, we create the different Angular 6 components and then assign different paths to the components. Attach the Routing progress bar so that user can feel the experience while navigating the various components.

Angular 6 Routing Example

We start this Angular 6 Routing Tutorial by installing the Angular in a local machine. Please make sure; you have installed Node.js in your local development environment.

#1: Install Angular 6 via Angular CLI.

Type the following command to install Angular CLI globally inside your computer.

npm install -g @angular/cli

# or

yarn add global @angular/cli

Now, create a local project using the following command.

ng new ng6routing

Now, start the application using the following command.

ng serve --open

It compiles and opens up the browser at this URL: http://localhost:4200

#2: Create three components using Angular CLI.

We can create our components using the following command.

ng g c components/news
ng g c components/market
ng g c components/tools

So, it will create three components inside components folder. So you can see all the three components inside src  >>  app  >>  components folder. The app.module.ts file will be automatically updated.

Angular 6 Routing Example

 

#3: Install Bootstrap 4.

Install using the following command.

npm i bootstrap@4.0.0 --save

Now, copy the bootstrap.min.css file from node_modules/bootstrap/dist/css folder and paste it inside src >> assets >> css directory.

Now, add the link inside src >> index.html file.

<!-- index.html -->

<link rel="stylesheet" href="/assets/css/bootstrap.min.css"/>

#4: Configure the Angular 6 Routing.

First, we need to register the RouterModule inside app.module.ts file.

// app.module.ts

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

 imports: [
    BrowserModule,
    RouterModule
  ],

Next step is the create an array of components with its path inside app.module.ts file.

// app.module.ts

const routes: Routes = [
  {
    path: 'news',
    component: NewsComponent
  },
  {
    path: 'market',
    component: MarketComponent
  },
  {
    path: 'tools',
    component: ToolsComponent
  }
];

Now, register these routes.

// app.module.ts

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

Now, you can output this routing component via the <router-outlet> component.

<!-- app.component.html -->

<router-outlet></router-outlet>

Save the file and go to the browser: http://localhost:4200/tools. If you see tools works! then you have configured routes correctly.

#5: Add Bootstrap 4 Navigation bar.

Inside app.component.html file, write the following code.

<!-- app.component.html -->

<nav class="navbar navbar-expand-lg navbar-light bg-light">
  <div class="collapse navbar-collapse" id="navbarSupportedContent">
    <ul class="navbar-nav mr-auto">
      <li class="nav-item active">
          <a routerLink="news" class="nav-link">News</a>
      </li>
      <li class="nav-item active">
          <a routerLink="market" class="nav-link">Market</a>
      </li>
      <li class="nav-item active">
          <a routerLink="tools" class="nav-link">Tools</a>
      </li>
    </ul>
  </div>  
</nav> <br />
<div class="container">
    <router-outlet></router-outlet>
</div>

Inside news.component.html file, write the following code.

<!-- news.component.html -->

<div class="card" style="width: 18rem;">
  <div class="card-body">
    <h5 class="card-title">News</h5>
    <p class="card-text">
        A sharp surge among financials, metals as well as FMCG names, especially in the last hour of trade, ensured that the market managed to close the week with good gains. The Nifty managed to clock 10,800 during the session and closed above the psychological mark. For the week, indices posted gains of around 1 percent.
    </p>
  </div>
</div>

Also, Inside market.component.html file, write the following code.

<!-- market.component.html -->

<div class="card" style="width: 18rem;">
    <div class="card-body">
      <h5 class="card-title">Market</h5>
      <p class="card-text">
          The D-Street is factoring a favourable Karnataka poll outcome on Tuesday, by a split exit poll result could cause a kneejerk reaction. Yet, the overall positive trend is likely to continue, suggest experts.
      </p>
    </div>
  </div>

Finally, Inside tools.component.html file, write the following code.

<!-- tools.component.html -->

<div class="card" style="width: 18rem;">
    <div class="card-body">
      <h5 class="card-title">Tools</h5>
      <p class="card-text">
          ONGC Videsh Ltd, India's flagship overseas oil investment firm, has dragged Sudan to an international arbitration court to recover over USD 400 million in unpaid oil dues pending since 2011. OVL, the overseas arm of state-owned Oil and Natural Gas Corp (ONGC), has filed an arbitration claim in a London court to recover about USD 300 million for oil Sudan bought from its Greater Nile Oil Project and another USD 98.94 million in unpaid pipeline rent lease, people familiar with the matter said.
      </p>
    </div>
  </div>

#6: Install ng2-slim-loading-bar library.

When we navigate to different routing components, we see the loading indicator. So for that, we need to install an ng2-slim-loading-bar library. So install using the following cmd.

npm install ng2-slim-loading-bar --save

Now, one of the significant change in Angular 6 is that Angular 6 now depends on TypeScript 2.7 and RxJS 6. So, if you install third-party packages right now, then it is not compatible with Angular 6.

To bridge the gap between Angular 6 and third-party packages, we need to install the following library. That is it.

npm i rxjs-compat --save

Now, import the SlimLoadingBarModule inside the app.module.ts file.

// app.module.ts

import { SlimLoadingBarModule } from 'ng2-slim-loading-bar';

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

Next step is, include the styling that comes with the library inside src  >>  styles.css file.

// styles.css

@import "../node_modules/ng2-slim-loading-bar/style.css";

#7: Adding Router Events.

Angular RouterModule gives us the following event modules.

  • NavigationStart
  • NavigationEnd
  • NavigationError
  • NavigationCancel
  • Router
  • Event

Now, write the following code inside app.component.ts file. I am writing the whole file.

// app.component.ts

import { Component } from '@angular/core';
import {SlimLoadingBarService} from 'ng2-slim-loading-bar';
import { NavigationCancel,
        Event,
        NavigationEnd,
        NavigationError,
        NavigationStart,
        Router } from '@angular/router';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
  constructor(private _loadingBar: SlimLoadingBarService, private _router: Router) {
    this._router.events.subscribe((event: Event) => {
      this.navigationInterceptor(event);
    });
  }
  private navigationInterceptor(event: Event): void {
    if (event instanceof NavigationStart) {
      this._loadingBar.start();
    }
    if (event instanceof NavigationEnd) {
      this._loadingBar.complete();
    }
    if (event instanceof NavigationCancel) {
      this._loadingBar.stop();
    }
    if (event instanceof NavigationError) {
      this._loadingBar.stop();
    }
  }

}

So, what it does is that, when Routing of the component starts, it also starts the Progress Loader and when the routing is complete, it completes the progress loader. If any error or cancellation, an event occurs then Routing Progressbar stops.

Now, the final step is to add the <ng2-slim-loading-bar color=“violet”></ng2-slim-loading-bar> in the app.component.html file. So, final app.component.html file looks like this.

<!-- app.component.html -->

<ng2-slim-loading-bar color="violet"></ng2-slim-loading-bar>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
  <div class="collapse navbar-collapse" id="navbarSupportedContent">
    <ul class="navbar-nav mr-auto">
      <li class="nav-item active">
          <a routerLink="news" class="nav-link">News</a>
      </li>
      <li class="nav-item active">
          <a routerLink="market" class="nav-link">Market</a>
      </li>
      <li class="nav-item active">
          <a routerLink="tools" class="nav-link">Tools</a>
      </li>
    </ul>
  </div>  
</nav> <br />
<div class="container">
    <router-outlet></router-outlet>
</div>

At last, our Angular 6 Routing Example is over. 

 

Post Your Thoughts

This site uses Akismet to reduce spam. Learn how your comment data is processed.

3 Comments