Table of Contents

Introduction

When you are going through any website, have you ever wondered why and how you are redirected to the Home page and not the About Us page while clicking the home link? The whole mechanism that decides what should be displayed when the user takes action is termed routing. You might be familiar with the jargon if you have already worked with any front-end frameworks.

Even if you haven’t, then that’s completely fine; because this blog will help you with steps to implement Angular routing and a Github repo also to come out of your ‘beginner zone.’ So, would you like to add Angular Routing and get started with the tutorial? Okay then! Let’s proceed with How to implement routing in Angular.

Goal

Before knowing how to build, let’s know what to build. Here’s the video of Angular routing example which we would be developing in this blog-

Steps to Implement Angular Routing

Install Angular CLI

Use the below-mentioned command to install Angular CLI in your system.

Globally-

Copy Text
npm install -g @angular/cli 

Locally-

Copy Text
npm install @angular/cli

Check Angular CLI version-

Copy Text
ng --version

The command will show you the version of Angular that you’ve just installed. You will see something like this on your terminal.

Angular CLI

Create and Configure Angular Routing Example

After the installation is done, we will create a brand new Angular project and configure it accordingly.

Create Angular project

Copy Text
ng new demo-app

NOTE- You can name it whatever you want instead of demo-app

Answer the series of questions, and you will successfully create your project. Make sure that you choose YES for – Would you like to add Angular routing?

Need support for routing and navigation in Angular?
Hire Angular developer from us to keep your Angular project up-to-date, implementing latest features to the stable release.

Configure Angular project

  • Angular Project structure-
Angular Project structure
  • Angular Generate Components-

Generate components for Home, Marvel movies, and DC movies using these commands, respectively.

Copy Text
ng g c home
ng g c marvel-movies
ng g c dc-movies

After running the commands, check your src/app. The project structure will look like this-

src/app

src/app

NOTE- The project structure can vary according to demo.

Install ng-bootstrap –

Copy Text
npm install bootstrap --save
npm install --save @ng-bootstrap/ng-bootstrap
ng add @ng-bootstrap/ng-bootstrap

Once you have implemented all the above commands open app.module.ts, and you’ll notice that the components and ng-bootstrap library has been imported and declared automatically.

app.module.ts

Copy Text
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import {NgbModule} from '@ng-bootstrap/ng-bootstrap';
 
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { MarvelMoviesComponent } from './marvel-movies/marvel-movies.component';
import { DCMoviesComponent } from './dc-movies/dc-movies.component';
 
@NgModule({
 declarations: [
   AppComponent,
   HomeComponent,
   MarvelMoviesComponent,
   DCMoviesComponent,
 ],
 imports: [
   BrowserModule,
   AppRoutingModule,
   NgbModule
 ],
 providers: [],
 bootstrap: [AppComponent]
})
 
export class AppModule { }

Let’s take a step ahead in Angular routing example and start with Basic Angular routing.

Implement Basic Angular routing in Angular Version 11

Basic Angular routing

We will be changing these two files-

  • app-routing.module.ts
  • app.component.html

app-routing.module.ts

In this file we will declare route with their respective components. So, the application would know which component has to be rendered on which route.

Copy Text
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { MarvelMoviesComponent } from './marvel-movies/marvel-movies.component';
import { DCMoviesComponent } from './dc-movies/dc-movies.component';
 
const routes: Routes = [
 {
   path: '',
   redirectTo: '/home',
   pathMatch: 'full',
 },
 {
   path: 'home',
   component: HomeComponent,
 },
 {
   path: 'marvel-movies',
   component: MarvelMoviesComponent
 },
 {
   path: 'dc-movies',
   component: DCMoviesComponent,
 },
];
 
@NgModule({
 imports: [RouterModule.forRoot(routes)],
 exports: [RouterModule]
})
 
export class AppRoutingModule { }

Explanation-

Copy Text
{
   path: '',
   redirectTo: '/home',
   pathMatch: 'full',
 },

Due to this above-mentioned code snippet, the site will be redirected to ‘/home’ when the application is launched, i.e., the component will render at ‘/home’ as your default page.

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

This code snippet indicates that HomeComponent is displayed on URL ‘/home’

The logic works same for other two components – MarvelMoviesComponent and DCMoviesomponent

app.component.html

The components are always rendered with the help of Router-Outlet of the parent component. And as app.component.html is the parent component of all the components, we will have the links for home page, marvel movies page, and dc movies page here.

app.component.html

Copy Text
<div  class="container"> 
  <nav class="navbar navbar-expand-lg navbar-light bg-light"> 
    <div class="collapse navbar-collapse header-nav" id="navbarNav"> 
       <ul class="navbar-nav" > 
         <li class="nav-item" > 
           <a class="nav-link" [routerLink]="['/home']">
             Home  
              </a >
               </li> 
               <li class="nav-item"> 
                <a class="nav-link" [routerLink]="['/marvel-movies']">
                  Marvel Movies 
                    </a>
                  </li> 
                <li class="nav-item"> 
              <a class="nav-link" [routerLink]="['/dc-movies']">
             DC Movies 
            </a>
           </li> 
          </ul> 
       </div>
         <span class="navbar-brand">Angular 11 Routing</span> 
    </nav> 
</div>

<router-outlet X</router-outlet>

Open the localhost and try whether you’ve done the routing correctly or not. It should be something like this (omitting the design part)-

NOTE: Here, I have changed the text in dc-movies.component.html and marvel-movies.component.html. You might see the default texts for both components. And plus, to keep it simple for beginners I have not made a common component for Marvel and DC rather I have used similar codes for both the components. You can choose to create a single component for both.

So, this was an example and explanation of Basic Angular routing. Now, taking one more step ahead and see how to implement Nested Routing and Routing with params.

Nested Angular Routing and Angular Routing with Params in Angular

Angular Project structure

Run below mentioned command to create MovieDetail component.

Copy Text
ng g c movie-detail

Your project structure in the app folder will be updated with this-

project structure

Now, let’s start coding.

1. Modifying the existing components

Marvel Movies and DC Movies As we need to change our Angular UI we will add the following lines of code in these files.

Marvel-movies marvel-

movies.component.ts ->Define a static array of movie objects.

marvel-movies.component.ts

Copy Text
import { Component, OnInit } from '@angular/core';
 
@Component({
 selector: 'app-marvel-movies',
 templateUrl: './marvel-movies.component.html',
 styleUrls: ['./marvel-movies.component.css']
})
export class MarvelMoviesComponent implements OnInit {
 
 public movies = [
   {
     id: "1",
     name: "CAPTAIN AMERICA: THE FIRST AVENGER",
   },
   {
     id: "2",
     name: "DOCTOR STRANGE",
   },
   {
     id: "3",
name: "IRON MAN",
   }
 ]
 constructor() { }
 
 ngOnInit(): void {
 }
}

marvel-movies.component.html -> Display each movie by using *ngFor.

marvel-movies.component.html

Copy Text
<div *ngFor="let movie of movies; let i = index"> 
     <button type="button"
           class="btn btn-primary btn-lg btn-block" 
             [routerLink]="movie.id"
             [state]="movie"
           >
        {{movie.name}} 
    </button> 
</div>

You can apply same code in the files (dc-movies.component.html, dc-movies.component.ts) of the component dc-movies

2. Modifying the file of Movie detail component

movie-detail.component.ts

Copy Text
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
 
 
@Component({
 selector: 'app-movie-detail',
 templateUrl: './movie-detail.component.html',
 styleUrls: ['./movie-detail.component.css']
})
export class MovieDetailComponent implements OnInit {
 
 public movieId;
 public movieData;
 
 constructor(private activatedRoute: ActivatedRoute) {
 }
 
 ngOnInit() {
   // to access data of movie
   this.movieData = history.state 
 
   // to access params
   this.movieId = this.activatedRoute.snapshot.params.id; 
 
   console.log("Params movieId", this.movieId);
 }
}

Explanation:
You might have guessed from the above snippet, what’s the exact use of ActivatedRoute. But if not, do not worry. Basically, ActivatedRoute helps us to get the route data. Suppose, if a situation arises, that we want to have a dynamic parameter in a route. For eg: /users/1 , /users/2 …. So here the /users/ is common, but the id gets updated. And if I want to fetch the data user-wise, we need to fetch the id from the URL. So to handle such scenarios, ActivatedRoute comes as a rescue.

We can access route data in two ways:
1. Using Snapshot
2. Using Observable (Subscribe).

I have shown (1) in the above snippet.

Use the Snapshot if you are pretty sure that you need an initial value of the parameter and the value would not change from the same component. As the name suggests, it would give you a snapshot of the initial value and would not catch the change after it.

Use the Observable if there are chances of change in the value of the parameter from the same component. As we are using observable, it would catch each change till we unsubscribe from it. If you are not sure about which to use, the safest option is to use the Observable.

You can use history.state to access the information about the selected movie and display it. Rather than that, if you have a different .json file, you can get the id from activatedRoute (here movieId) and then filter the data based on the id.

3. Modifying the file related to Routing

app-routing.module.ts

Import this –

Copy Text
import { MovieDetailComponent } from 
'./movie-detail/movie-detail.component';

Change the routes for Marvel and DC movies-

Copy Text
const routes: Routes = [
 {
   path: '',
   redirectTo: '/home',
   pathMatch: 'full',
 },
 {
   path: 'home',
   component: HomeComponent,
 },
 {
   path: 'marvel-movies',
   children: [
     {
       path: '',
       component: MarvelMoviesComponent
     },
     {
       path: ':id',
       component: MovieDetailComponent
     }
   ]
 },
 {
   path: 'dc-movies',
   children: [
     {
       path: '',
       component: DCMoviesComponent,
     },
     {
       path: ':id',
       component: MovieDetailComponent
     }
   ]
 },
];
 
@NgModule({
 imports: [RouterModule.forRoot(routes)],
 exports: [RouterModule]
})
export class AppRoutingModule { }

Explanation –

  • children attribute consist of various child routes, which you want to add after /marvel-movies.
  • When the URL matches route /marvel-movies, MarvelMoviesComponent is displayed because of this –
Copy Text
{
  path: '',
  component: MarvelMoviesComponent
 },
  • When the URL matches route- /marvel-movies/:id, MovieDetailComponent is displayed because of this-
Copy Text
{
  path: ':id',
  component: MovieDetailComponent
}   

You can apply the same lines of code for DC movies component too.
Your localhost will look something like this if you have implemented the code as directed above (omitting the design part).

So far, so good? This was all about Basic Angular Routing and Nested Angular Routing, and Angular Routing with params in Angular v11. In next blog, I will let you know how to load the routes lazily.

Conclusion

Even after developing various demo you might need help when you want to implement Angular app router in Angular v11 for large-scaled Angular projects. And for that, we are to lend a helping hand. Without wasting a single minute connect to Bacancy Technology to work with best Angular developers.

To fulfill your varied project requirements, we let you hire Angular developer from us at your convenience who have in-depth knowledge and extensive expertise in dealing with all the shapes and sizes of Angular projects.

Outsource Team of Angular Developers

  • Well experienced team
  • Skilled and experienced programmers
  • Flexible hiring models

BOOK A 30 MIN CALL

Build Your Agile Team

Hire Skilled Developer From Us

[email protected]

Your Success Is Guaranteed !

We accelerate the release of digital product and guaranteed their success

We Use Slack, Jira & GitHub for Accurate Deployment and Effective Communication.

How Can We Help You?