angular routing

In this tutorial, you will drive through all the essential concepts on Angular Routing. I will cover the following topics in this article:

  1. Introduction to Angular Routing
  2. Prerequisites for Angular Routing
    1. HTML
    2. CSS
    3. JavaScript
    4. Angular CLI
  3. Installation of Angular Routing
    1. Installation of Node.js
    2. Installation of Angular CLI
    3. Installation of Angular Material
    4. Creating Your Angular Routing Project
  4. Routing between App and First Components
  5. Routing between Other Components
  6. Routing through Buttons
  7. Special String Path

Let’s kickstart our Angular Routing tutorial with its introduction.

Introduction to Angular Routing

Navigating from one page to another page in a web application is known as Routing. Routing in Angular is called Angular Routing. Below is a familiar model of application navigation which a web browser follows:

  • The web browser navigates to a corresponding page when you enter a URL in the address bar
  • The browser navigates to a new page when you click a link on the page
  • When you click the browser’s forward and backward buttons, it navigates to the corresponding pages through the history of pages you have visited

The Angular Router adopts from this model for navigation. Angular is a Single Page Application (SPA) that uses multiple Angular routes. In SPA, all the functionalities of your application exist in a single HTML page. The browser renders only the parts that are required for the user rather than loading a new page.

Prerequisites for Angular Routing

1. HTML

  • Stands for Hypertext Markup Language
  • It is a markup language for creating web pages/documents

General Syntax: 

<!DOCTYPE html>
<html>
<head>
<title>Title of the Page</title>
</head>
<body>
<h1>Welcome to Great Learning!</h1>
</body>
</html>

2. CSS

  • Stands for Cascading Style Sheets
  • It is more responsible for the look and feel of the webpage
  • You can select elements from HTML and apply styling to it

General Syntax:

selector {
property1 : value1; 
property2 : value2; 
property3 : value3;
}

3. JavaScript

It is scripting or programming language, which allows you to implement complex features on web applications.

  • Arrays
  • Objects
  • Functions
  • Control Flow Statements
  • DOM Manipulation
  • DOM Events
  • Closure
  • Prototype
  • OOPs

General Syntax:

<script>
//JavaScript Code
</script>

4. Angular CLI

Angular CLI is a command-line interface tool that helps generate, develop, and maintain Angular projects directly from a command shell.

With the knowledge of these prerequisites, you can ensure that you can clearly understand the tutorial of Angular Routing.

Installation of Angular Routing

Now that you have a basic understanding of Angular Routing, let’s begin with the tutorial on the installation of Angular Routing to your application.

Firstly, you must install the Node Package Manager, i.e. npm and Angular CLI on your system. 

Installation of Node.js

Step-1: You need to download the Node Package Manager from its official website:
https://nodejs.org/en/download/

Step-2: You will see different kinds to install Node.js. I will choose Windows as it suits my system configurations. You can select any configuration that is suitable for your system.

Step-3: Once the software is downloaded, open the file to run the setup. An installation wizard window will appear. Choose ‘Next’ to move further into the installation process.

Step-4: Next, tick the ‘I Agree with the terms and conditions’ checkbox that pops up. Later, choose the location where you want to install Node.js on your system and click the ‘Next’ button.

Step-5: The custom setup appears. You don’t need to change anything. Just click ‘Next’ to the move to the next step.

Step-6: Now, it will ask whether you want to install ‘Chocolatey’ or not. Chocolatey is an NPM for Windows, which illustrates proper package management concepts, allowing you to version things, manage dependencies and the order of installation, adequate inventory management, and other numerous features. So, I recommend you to install it as it is a convenient tool.

Click on the checkbox and choose the ‘Next’ button.

Step-7: Next, click the ‘Install’ button for the installation. After the installation, the final window pops up saying ‘Completed the Node.js Setup Wizard’. Click ‘Finish’, and Node.js is good to go.

Step-8: To verify whether the installation is successful, type the command ‘node -v’ to check for the version.

As displayed in the above image, you can ensure that the installation of Node.js is successful.

Installation of Angular CLI

Step-1: To install Angular CLI, type the following command:

npm install -g @angular/cli

The command will download and install the latest Angular CLI version globally (the -g extension) on your device. 

Step-2: Google will ask you the following question:

“Would you like to share anonymous usage data with the Angular Team at Google under Google’s Privacy Policy at https://policies.google.com/privacy?”

You can either type ‘yes’ or ‘no’ that depends on yourself.

Step-3: Angular CLI will be installed, and to verify it, type the following command:

ng --version

As displayed in the above image, you can ensure that the installation of Angular CLI is successful.

Installation of Angular Material

Angular Material is a UI (User Interface) component library for Angular. You can design your application in an organised manner and attract users with unique designs like styles and shapes. Angular Material drives your application to become more consistent, fast, versatile, and design responsive websites.

Step-1: Moving ahead, change the path directory to your Angular project and type the following command:

ng add @angular/material

It will ask you to select a prebuilt or a custom theme, as shown below:

Step-2: Choose the “Indigo/Pink” prebuilt theme. It is the default theme to style your application. If you select the “Custom” theme, you can customise your theme files that include all common styles.Step-3: Next, type ‘y’ to set up global Angular Material typography styles.

Step-4: Type ‘Y’, i.e., ‘Yes’ to set up browser animations for Angular Material. 

Browser animations help in making your application more fun and easier to use. They help in improving your app and user experience that attracts the attention of users.

Eventually, Angular Materials will be installed on your project.

Creating Your Angular Routing Project: Now, create a directory or folder called ‘Angular Routing’ and change the path to this directory using the cd command on your Windows Command Prompt or any other CLI which you are using. You need to type the following command to change the path and navigate into the directory:

cd C:/Users/Your_System_Name/Desktop/Angular Routing

The path mentioned above is where I will create a new Angular project on my system to teach you about Angular Routing.

To create a new Angular project, type the following command:

ng new angular-routing-tutorial

First, it will ask you to enforce stricter type checking and stricter bundle budgets in the workspace, as shown below:

Choose ‘y’, i.e., ‘yes’ so that this setting helps you improve maintainability and catch bugs ahead of time. Next, it will ask you to add Angular Routing to your project.

Type ‘y’ to add Angular Routing to your project. Moving further, it will ask you to choose a styling format.

Choose ‘CSS’ for installing the default CSS stylesheet on your web application. The stylesheet will comprise all the other stylesheets. 

Now, click the ‘Enter’ button and eventually, your new angular-routing-tutorial project will be created in your directory. Navigate to your project by typing the following command:

cd angular-routing-tutorial

Suppose, you have already created an Angular project and would like to add Angular Routing to the existing project, you can effortlessly type the following command:

ng generate module app-routing --module app --flat

The command will add routing to your existing project generating the app-routing.module.ts file into your angular-routing-tutorial/src/app directory. The generated file will have the following code:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
const routes: Routes = [];
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Routing between App and First Components

First, I will begin with how to navigate from the App component to the First component. Moving ahead, generate a component named first using any of the following commands:

ng generate component first

OR

ng g c first

The command will create the first component in the src/app directory. The file comprises the following sub-components:

  1. first.component.css
  2. first.component.html
  3. first.component.spec.ts
  4. first.component.ts

To navigate between the App and First components, open the app.component.html file on your project and erase all the existing code. Next, write the new code as follows:

<mat-toolbar color="primary">
  <span>Angular Routing Tutorial: Great Learning</span>
</mat-toolbar>
<router-outlet></router-outlet>

<router-outlet> is a router directive from the router library. It guides the router where to display the routed views.

<mat-toolbar> is a component from Angular Material, used for headers and titles. You can change the color of the Toolbar using the color property. By default, a neutral background colour is used by toolbars, which is based on the current theme, i.e. either light or dark. You can opt for three default themes: ‘primary’, ‘accent’, or ‘warn’.To use this toolbar, import it in the app.module.ts file from angular/material using the following command:

import { MatToolbarModule } from '@angular/material/toolbar';

Now, add the MatToolbarModule module in the imports: [ ] section located in the app.module.ts file.

imports: [
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    MatToolbarModule
],

Now, execute your project by running the following command:

ng serve -o

The command opens your project on the default browser of your system, which is as follows:

Now, I will create a route for your first component. Open the first.component.html file to write the code for displaying the contents of the page.

<h2>The First component welcomes you!</h2>

Now, import ‘FirstComponent’ in the app-routing.module.ts file, as shown below:

import { FirstComponent } from './first/first.component';

Moving ahead, open the app-routing.module.ts file to create a path for the first component in the Routes=[ ] section.

const routes: Routes = [
  { path: 'first', component: FirstComponent }
];

The code will create a route for the first component. You can view the component using the following URL on your browser:

http://localhost:4200/first

The URL will display the contents of the first component file, as follows:

Routing between Other Components

Here, you will learn how to navigate from one component to another. Like the first component, you need to first generate another component, let’s say ‘second’. Type the following command to generate it:

ng g c second

Moving forward, we will add a route in the first.component.html file to link with the second.component.html file.

<h2>The First component welcomes you!</h2>
<nav>
    <a routerLink = "/second">Click here to navigate to the Second component</a>
</nav>

Next, we will create a route for the second component, similar to the first component. Open the second.component.html file to write the code for displaying the contents of the page.

<h2>The Second component welcomes you!</h2>

Now, import ‘SecondComponent’ in the app-routing.module.ts file, as shown below:

import { SecondComponent } from './second/second.component';

Moving further, open the app-routing.module.ts file to create a path for the second component in the Routes=[ ] section.

const routes: Routes = [
  { path: 'first', component: FirstComponent },
  { path: 'second', component: SecondComponent }
];

The code will create a route for the second component. 

First, execute your project by running the following command on your console:

ng serve -o

Next, open the first component using the following URL on your browser:

http://localhost:4200/first

The URL will display the contents of the first component file, as follows:

Click on the “Click here to navigate to the Second component” link to open the second component page and display its contents.

Routing through Buttons

Let’s start with navigating through buttons. Firstly, generate two components, namely, ‘data-science-course’ and ‘devops-course’ in your project.

Data Science Course: ng g c data-science-course

DevOps Course: ng g c devops-courseLater, I will add a “Homepage” icon and “Courses” menu option to your project. Open the app.component.html file and redraft your code as follows:

<mat-toolbar color="primary">
  <span>Angular Routing Tutorial: Great Learning</span>
  <span class="home-space"></span>
  <button class="example-container" mat-icon-button routerLink="/">
     <mat-icon inline="true" aria-hidden="false" aria-label="Example home icon">home</mat-icon>
  </button> 
  <span class="space"></span>
  <button class="buttons" mat-button [matMenuTriggerFor]="menu">Courses</button>
  <mat-menu #menu="matMenu">
     <button mat-menu-item routerLink="/data-science-course">Data Science</button>
     <button mat-menu-item routerLink="/devops-course">DevOps</button>
  </mat-menu>
</mat-toolbar>
<router-outlet></router-outlet>

In the above HTML code, routerLink=”/” refers to the path to your first page URL i.e. http://localhost:4200. Next, <mat-icon> and <mat-menu> are components from Angular Materials, that represent various icons and menu options respectively. To use these components, import MatIconModule and MatMenuModule just like you did for MatToolbarModule from the ‘@angular/material’ directory, in your app.module.ts file.

import { MatIconModule } from '@angular/material/icon';
import { MatMenuModule } from '@angular/material/menu';

Now, add MatIconModule and MatMenuModule in the imports: [ ] section located in the app.module.ts file.

imports: [
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    MatToolbarModule,
    MatIconModule,
    MatMenuModule
],

Proceeding further, write the following code in the app.component.css file.

.space{
    flex: 1 1 auto;
} 
.home-space{
    flex: 20 0 auto;
} 
.buttons{
    width: 100px;
    height: 40px;
    font-size: 15px;
    border-radius: 10px;
    border: 1px solid #113c89;
    background-color: #ffcccc;
    cursor: pointer;
}
.example-container {
    background-color: Transparent;
    background-repeat:no-repeat;
    font-size: 35px;
    height: 35px;
    border: none;
    cursor:pointer;
    overflow: hidden;
    outline:none;
    color: white;
}

The above CSS code will place and style the ‘Homepage’ icon and the ‘Courses’ menu option as per the provided criteria. 

Later, follow the same procedure as you did earlier to create routes for data-science-course and devops-course components.Import ‘DataScienceCourseComponent’ and ‘DevopsCourseComponent’ in the app-routing.module.ts file, as shown below:

import { DataScienceCourseComponent } from './data-science-course/data-science-course.component';
import { DevopsCourseComponent } from './devops-course/devops-course.component';

In the same app-routing.module.ts file, create a path for data-science-course and devops-course components in the Routes=[ ] section.

const routes: Routes = [
  { path: 'first', component: FirstComponent },
  { path: 'second', component: SecondComponent },
  { path: 'data-science-course', component: DataScienceCourseComponent },
  { path: 'devops-course', component: DevopsCourseComponent }
];

The code will create routes for both components. You can now navigate through buttons.

To implement it, execute your project by running the following command:

ng serve -o

Click on either ‘Data Science’ or ‘DevOps’ buttons to navigate to their respective pages.

Data Science Button:

DevOps Button:

Now, click on the ‘Home’ icon to redirect to your home page, as shown below:

Special String Path

The Special String (**) redirects to your defined path, i.e., your home page if the requested URL doesn’t match any of your defined paths or routes. You can add the special string path in the Routes=[ ] section, located in the app-routing.module.ts file of your project.

const routes: Routes = [
  { path: 'first', component: FirstComponent },
  { path: 'second', component: SecondComponent },
  { path: 'data-science-course', component: DataScienceCourseComponent },
  { path: 'devops-course', component: DevopsCourseComponent },
  { path: '**', redirectTo: '', pathMatch: 'full' }
];

In the above code snippet, you could see the defined paths in your project. Below is an example of implementing the special string path. 

First, execute your project using the ‘ng serve -o’ command. Then, type the following address in the URL section of your browser: http://localhost:4200/third

As you can see, the third component doesn’t exist in your defined paths. Hence, your application will be redirected to your home page URL, which is: http://localhost:4200/

Your browser will display the contents of your home page.

Conclusion

With this, I would like to sum up the article. I hope you are satisfied with my tutorial on all the basic fundamentals of Angular Routing and clear with all the hands-on demos of various sub-topics. 

As you read above, routing with SPAs is much easier and faster. The browser rendered only the necessary essentials.

If you have any queries or feedback, drop us your comments in the comments section below and our experts will revert to you.

If you wish to learn more about this concept, you can check out Great Learning Academy’s Free Online Course on Introduction To AngularJS.

0

LEAVE A REPLY

Please enter your comment!
Please enter your name here

two + seven =