Angular Routing Tutorial

When we imagine a website, the following things come to our mind. 

  • Some cool header with a company logo and title along with a welcome message.
  • Some footer with copyright messages.
  • Some dynamic content making the website really useful.

Did we miss anything? Something more important and useful? Yes, the menu items. Menu items let us navigate between different content (or pages) of an application. A web application without navigation is not an application. 

Angular is a popular framework used for creating a single page application. Let’s start our discussion with understanding what a Single Page Application or SPA is.

Single page application (SPA)

A single-page application (SPA) is an approach in which we create a website design where each new page is not served from the server but generated dynamically through JavaScript's ability to manipulate the DOM elements on the existing page itself.

Routing

Considering you have the basic knowledge on Angular, I believe you know that Angular helps to create UI as the combination of compatible and reusable web components. So, when we say navigation in an Angular application, it simply means navigating between those components. It can be achieved by implementing routing.

Routing is a simple mechanism in a web application by which the requests are routed to the code that handles them. A framework is instructed with the help of some code for what code to be executed when a request is received with some URL.

In Angular, routing can be achieved using an Angular module called “RouterModule”. It is defined inside “@angular/router”.

      Case 1: url: localhost/login                    Case 2: localhost/home

Angular Routing   Angular Routing
 

The Router Outlet

 
The Router-Outlet is a directive exported by RouterModule and acts as a placeholder that indicates the router where it needs to insert the matched component.
 

The Navigation Directive

The Angular Router provides two directives for navigation. The routerLink directive replaces the href attribute of anchor(<a>) tags to create links and routerLinkActive is used for making the active link.

For example.

  1. <a [routerLink]="/products" [routerLinkActive]="/products">Products</a>  

Note
Please note that Routing has nothing to do with menus. It is simply about URL and code to be executed. To a framework, how the request is made is not countable.

Enough theory. Let's start with a simple example and understand it in more details.

Prerequisite knowledge

 

  • Fundamental knowledge of TypeScript, HTML, and Angular.
  • Make sure the Angular CLI is installed in the machine.

 

STEP 1 - Create an Angular project

Now, let us create one project called RoutingExample.

> ng n RoutingExample

STEP 2 - Make three components for the application

Create one directory inside src >> app folder called components.

Generate three components inside the components directory.

> ng g c component/home
> ng g c component/about
> ng g c component/login

After generating components,the app.module.ts file should look like this.

  1. import { NgModule } from '@angular/core';  
  2. import { BrowserModule } from '@angular/platform-browser';  
  3.   
  4. import { AppComponent } from './app.component';  
  5. import { HomeComponent } from './components/home/home.component';  
  6. import { AboutComponent } from './components/about/about.component';  
  7. import { LoginComponent } from './components/login/login.component';  
  8. @NgModule({  
  9.    imports: [ BrowserModule ],  
  10.    declarations: [ AppComponent,  
  11.    AboutComponent,  
  12.    HomeComponent,  
  13.    LoginComponent ],  
  14.    bootstrap: [ AppComponent ]  
  15. })  
  16. export class AppModule { }  
  17.   
  18. <!-- app.component.html -->  
  19.    <div style="text-align:center">  
  20.       <h1>  
  21.          Welcome to Just Compile!!  
  22.       </h1>  
  23.       <home></home>  
  24.       <about></about>  
  25.       <login></login>  
  26. </div>  

Let us check the output by executing the ng serve command.

Angular Routing

Now, this is not a SPA. Our target is to display only one component at a time with a menu at the top for navigating. The next step is to create a menu component.

Create a menu component in src>>app directory.

> ng g c Menu

Before creating the menu, let us import bootstrap in our application for a better design.

Go to index.html file and paste the below links.

  1. <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/boo  
  2. tstrap.min.css">  
  3. <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">  
  4. </script>  
  5. <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js">  
  6. </script>  

Now, open menu.component.html and write the below code.

  1. //index.html  
  2. <div class="container">  
  3. <nav class="navbar navbar-inverse">  
  4.  <div class="container-fluid">  
  5.    <div class="navbar-header">  
  6.      <a class="navbar-brand"                                       
  7.         href="https://www.justcompile.com/">Just Compile</a>  
  8.    </div>  
  9.    <ul class="nav navbar-nav">  
  10.      <li><a href="#">Home</a></li>  
  11.      <li><a href="#">About</a></li>  
  12.      <li><a href="#">Login</a></li>  
  13.     </ul>  
  14.   </div>  
  15.  </nav>  
  16. </div>  

Let us check the output by executing the ng serve command.

Angular Routing

STEP 3 - Adding routing in the application

The Angular Router enables the navigation in an Angular project.

To use Angular Router, we need to import RoutingModule from @angular/router library inside our app.module.ts file.

  1. // app.module.ts  
  2. import { RouterModule } from '@angular/router';  
  3. imports: [  
  4. BrowserModule, RouterModule  
  5. ],  

For the navigation, now we need to configure the routes for the Angular project. In routes, we need to declare the path for the corresponding component. Let us create routerConfig.ts in src>>app directory in which we will define the routes for our project.

  1. // routerConfig.ts  
  2. import { Routes } from '@angular/router';  
  3. import { HomeComponent } from './components/home/home.component';  
  4. import { AboutComponent } from './components/about/about.component';  
  5. import { LoginComponent } from './components/login/login.component';  
  6. export const appRoutes: Routes = [  
  7.                             { path: 'home', component: HomeComponent },  
  8. { path: 'about',component: AboutComponent},  
  9.        { path: 'login',component: LoginComponent}];   

Now, import this object inside app.module.ts and register the module.

  1. // app.module.ts  
  2. import appRoutes from './routerConfig';  
  3. imports: [  
  4.    BrowserModule,  
  5.    RouterModule.forRoot(appRoutes)  
  6. ],  

Now, add the navigation directive to the menu component.

  1. <div class="container">  
  2. <nav class="navbar navbar-inverse">  
  3.  <div class="container-fluid">  
  4.    <div class="navbar-header">  
  5.      <a class="navbar-brand"                                       
  6.         href="https://www.justcompile.com/">Just Compile</a>  
  7.    </div>  
  8.    <ul class="nav navbar-nav">  
  9.      <li><a routerLink="home">Home</a></li>  
  10.      <li><a routerLink="about">About</a></li>  
  11.      <li><a routerLink="login">Login</a></li>  
  12.     </ul>  
  13.   </div>  
  14.  </nav>  
  15. </div>  

STEP 4 - DEFINE ROUTER OUTLET.

All the settings are done now. It is time to use routing in our project. The router module gives us a selector named router-outlet. Using this selector in our app.component.html, we actually are telling our HTML file to find the component according to the path defined. In our case, we defined a path in routerConfig.ts file.

Write the below code in app.component.html.

  1. <!-- app.component.html -->  
  2.    <menu></menu>  
  3. <router-outlet></router-outlet>  

Start the app by executing the following command.

> ng serve --open


                                              
Conclusion

Are we done? Definitely not! As you can see, currently all components are loaded in the start itself. What if your projects have 1000 components? Won't it increase the load on an application? The answer is “YES” and that’s where the lazy loading comes into the picture and that’s what my next article will talk about.


Similar Articles