Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • AngularJS Tutorial
  • AngularJS Directives
  • AngularJS Functions
  • AngularJS Filters
  • AngularJS Examples
  • AngularJS Interview Questions
  • Angular ngx Bootstrap
  • AngularJS Cheat Sheet
  • AngularJS PrimeNG
  • JavaScript
  • Web Technology
Open In App
Next Article:
How to Create a new module in Angular ?
Next article icon

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

  • Install Node Js and npm Package
  • Angular CLI
  • Install a text Editor (VS code)

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
How to Create a new module in Angular ?

K

kuldeep470
Improve
Article Tags :
  • Web Technologies
  • AngularJS
  • AngularJS-Service

Similar Reads

  • How to create module with Routing in Angular 9 ?
    Angular applications are modular, and NgModules is Angular's own modular architecture. NgModules are containers for closely integrated application domains, workflows, or feature sets that comprise cohesive code blocks. Their scope is governed by the NgModule they include, and they can contain compon
    4 min read
  • Introduction to Angular Concepts
    Angular, a powerful front-end framework developed by Google, has revolutionized the way modern web applications are built. For newcomers to web development, Angular can seem to be a great choice due to its features, concepts, and terminologies. In this article, we'll see more about the journey of An
    5 min read
  • How to create a new component in Angular?
    A component in Angular is the building block for making web pages. It is a reusable block of code that can be used anywhere in the app any number of times. It provides scalability, reusability, and readability. Each component does a specific job like showing a menu, a photo or a card, etc. In this a
    3 min read
  • Introduction To Components And Templates in Angular
    Angular is a powerful framework for building dynamic, single-page web applications. One of the core concepts that make Angular so effective is its use of components and templates. Components and templates are the building blocks of any Angular application, allowing developers to create reusable, mai
    6 min read
  • How to Create a new module in Angular ?
    Modules are most important when it comes to building strong and scalable Angular applications. They help organize your code, promote modularity, and improve maintainability. It encourages collaboration among developers by grouping related components, directives, pipes, and services. In this article,
    3 min read
  • How to setup 404 page in angular routing ?
    To set up a 404 page in the angular routing, we have to first create a component to display whenever a 404 error occurred. In the following approach, we will create a simple angular component called PagenotfoundComponent.  Creating Component: Run the below command to create pagenotfound component. n
    2 min read
  • How to bundle an Angular app for production?
    Introduction Before deploying the web app, Angular provides a way to check the behavior of the web application with the help of a few CLI commands. Usually, the ng serves command is used to build, watch, and serve the application from local memory. But for deployment, the behavior of the application
    4 min read
  • How to detect a route change in AngularJS ?
    In this article, we will see how to detect a route change in AngularJS. In order to detect route change at any moment in AngularJS, this can be achieved by using the $on() method. The $on() method is an event handler, the event which will handle $routeChangeSuccess which gets triggered when route/vi
    2 min read
  • AngularJS Questions Complete Reference
    AngularJS is a JavaScript open-source front-end framework that is mainly used to develop single-page web applications(SPAs). It is a continuously growing and expanding framework which provides better ways for developing web applications. This is the most used framework in India compare to other fron
    8 min read
  • Routing in Angular 9/10
    Routing in Angular allows the users to create a single-page application with multiple views and allows navigation between them. Users can switch between these views without losing the application state and properties. Approach: Create an Angular app that to be used.Create the navigation links inside
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences