Open In App

A Complete Guide To Angular Routing

Last Updated : 23 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Angular Routing is a technology to build single-page applications that provide multi-page services at a single port. It enables seamless navigation and loading of the different pages. When an Angular app is started then the whole component is only loaded at once and dynamically reloads the requested pages through routing technology.

WhatsApp-Image-2024-07-02-at-52016-PM
Angular Routing

This tutorial is going to give you a complete guide to How Angular Routing actually works and what are the features and their advantages. At the end of this tutorial you will be able to implement routing feature in your Angular Project and also you will have a clear idea about how angular routing makes an application very efficient by loading only those component instead of whole pages which has requested by an user.

Introduction to Angular Routing

The Angular router is a core part of the Angular application and is responsible for mapping URLs to components and rendering different components based on the current URL matches in an Angular application.

  • We should have clear idea about this Routing feature, it is responsible for page rendering not for navigating links. Many times developers have misconception that when we click navigation bar then page will change but the scenario is different whenever we interact with any navigation elements then it only set the URL or we can say change the URL.
  • After changing the URL, the responsible Angular Routing Module notes down the new URL and then renders components accordingly.

Prerequisites

Steps to Create an Angular Application

Step 1: After the global setup of Node Js and npm Packages now we have to install Angular globally by using the below mentioned command

npm install -g @angular/cli

Step 2: Run the command below to create a new Angular Application.

ng new project_name

Step 3: Change the directory using below command to enter in our Project environment.

cd project_Name

Step 4: Run the command below to create components.

ng generate component Home
ng generate component About
ng generate component Contact

Step 5: Run the below command to start the server.

ng serve

Dependencies

"dependencies": {
"@angular/animations": "^18.1.0",
"@angular/common": "^18.1.0",
"@angular/compiler": "^18.1.0",
"@angular/core": "^18.1.0",
"@angular/forms": "^18.1.0",
"@angular/platform-browser": "^18.1.0",
"@angular/platform-browser-dynamic": "^18.1.0",
"@angular/platform-server": "^18.1.0",
"@angular/router": "^18.1.0",
"@angular/ssr": "^18.1.0",
"express": "^4.18.2",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"zone.js": "~0.14.3"
}

Folder Structure

Screenshot-2024-04-22-055152
Folder Structure
HTML
<!-- app.component.html -->

<h1>Angular Router App</h1>
<nav>
    <ul>
        <li><a routerLink="/" routerLinkActive="active" ariaCurrentWhenActive="page">
          Home</a></li>
        <li><a routerLink="/about" routerLinkActive="active" ariaCurrentWhenActive="page">
          About</a></li>
        <li><a routerLink="/contact" routerLinkActive="active" ariaCurrentWhenActive="page">
          Contact</a></li>
    </ul>
</nav>
<router-outlet></router-outlet>
HTML
<!-- home.component.html -->
	
	<p>Home Component</p>
HTML
<!-- about.component.html -->
	
	<p>About Component</p>
HTML
<!-- contact.component.html -->
	
	<p>Contact Component</p>
JavaScript
// app.routes.ts

import { Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';
import { ContactComponent } from './contact/contact.component';

export const routes: Routes = [
    { path: '', component: HomeComponent },
    { path: 'about', component: AboutComponent },
    { path: 'contact', component: ContactComponent }
];
JavaScript
//app.component.ts

import { Component } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { RouterLink, RouterLinkActive } from '@angular/router';

@Component({
    selector: 'app-root',
    standalone: true,
    imports: [RouterOutlet, RouterLink, RouterLinkActive],
    templateUrl: './app.component.html',
    styleUrl: './app.component.css'
})
export class AppComponent {
    title = 'route';
}


Example :- Step to run the application: Open the terminal and type the following command -

  1. The file app.component.html includes the main page where rendering process start and ends .
  2. The file app.routes.ts is basically for enlisting all the Route related components.
  3. The file home.component.html simply includes home component elements.
  4. The file about.component.html simply includes About component elements.
  5. The file contact.component.html simply includes Contact component elements.
ng serve

Output :


We can see :

  • Home component at : http://localhost:4200/
  • About component at : http://localhost:4200/about
  • Contact Component at : http://localhost:4200/contact

Some Important Angular routing concepts

1. Child Routes

Child routes in Angular are used to create nested routes within a parent route. This is useful for organizing routes that share a common path or component structure. You might have a main component with several sub-components, each accessible via its own route. It can be implemented like -

const routes: Routes = [
{
path: 'parent',
component: ParentComponent,
children: [
{
path: 'child1',
component: Child1Component
},
{
path: 'child2',
component: Child2Component
}
]
}
];

2. Lazy Loading

Lazy loading is a technique used to load feature modules on demand rather than upfront. This improves the performance of your application by loading only the necessary parts initially and loading additional parts as needed.

To implement lazy loading, you define a route with the 'loadChildren' property instead of 'component'. This property points to a function that returns the module to be loaded.

const routes: Routes = [
{
path: 'feature',
loadChildren: () => import('./feature/feature.module').then(m => m.FeatureModule)
}
];

3. Route Guards

Route guards are used to control access to certain routes based on conditions such as authentication status, user roles, or other criteria.

Angular provides several types of route guards -

  • CanActivate: Determines if a route can be activated.
  • CanDeactivate: Determines if a route can be exited.
  • CanActivateChild: Determines if child routes can be activated.
  • CanLoad: Determines if a module can be loaded.


Here is the some Functions and Module explanation which are used in above code snippet :-

  • RouterOutlet : Directive to specify where the router should render the active component.
  • RouterLink : Directive to create links to other routes.
  • RouterLinkActive : Directive to highlight the active link in your navigation bar.
  • ActivatedRoute : Service to access information about the current route, such as the route parameters.
  • NavigationExtras : Object to pass additional data to the router when navigating to a new route.

Finally, we well-versed through Angular Routing and now you are able to implement Routing in your Angular Project.


Next Article

Similar Reads