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:
Routing in Angular JS using Angular UI Router
Next article icon

What is Routing and Nested Routing in Angular 9/8 ?

Last Updated : 15 Aug, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will learn the routing & nested routing concept in Angular. We will implement the concept to establish routing between different components by making their routes when a user clicks the link, it will be navigated to a page link corresponding to the required component. Let’s understand the routing in Angular. 

Routing: Angular provides extensive navigation functions for simple scenes that are too complex. Defining navigation items and corresponding views is called routing. Routing 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. Angular provides a separate router module for adjusting navigation in the application. In this article, we will know how to perform routing and nested routing in an Angular application.

Syntax:

ng new app_name
  • For routing, you will need components. Use the below command to create the component.

    Syntax:

    ng g c component_name

    Routing means navigation and Nested-Routing mean sub-navigation or sub-page navigation. Here, we will make three main links name as Home, ContactUs, AboutUs. Inside the about-us component, we will create another two sub-components name as ourCompany & ourEmployees.

  • In app.module.ts, import RouterModule, Routes from @angular/router.

    Syntax:

    import { RouterModule, Routes } from '@angular/router';
  • Then in imports of app-routing.module.ts define the paths.
    const routes: Routes = [   { path: '', component: HomeComponent },   { path: 'aboutus', component: AboutUsComponent },   { path: 'contactus', component: ContactUsComponent }  ];    @NgModule({   imports: [RouterModule.forRoot(routes)],   exports: [RouterModule]  })
  • Define routerLink’s path as the component name in the app.component.html in HTML.
    <a class="active" href="#home" routerLink="/">Home</a>  <a href="#contact" routerLink="/contactus">Contact</a>  <a href="#about" routerLink="/aboutus">About</a>
  • Apply router-outlet for your application in app.component.html. The routed views render in the <router-outlet>.
    <router-outlet></router-outlet>
  • Define the HTML for about-us.component.html, contact-us.component.html & home.component.html.
  • Now angular web app is ready to run.

Project Structure: Our project structure will look like the following image:

Project Structure

Let’s follow the steps to build the routing & nested routing for the application.

Step 1: Creating Simple Angular Application. In this step, we will create a simple angular application as an example using the command line argument. We need to run this below command on the command prompt:

ng new geeksforgeeks-routing

Once we run this command, on the command prompt, two things will be asked for creating a routing module and we need to answer yes.

 

Step 2: In this step, after the successful installation process, we will update our app.component.html with the given HTML code.

app.component.html

<!DOCTYPE html>
<html>
  <head>
    <style>
      ul {
        list-style-type: none;
        margin: 0;
        padding: 0;
        overflow: hidden;
        background-color: #333;
      }
  
      li {
        float: left;
      }
  
      li a {
        display: block;
        color: white;
        text-align: center;
        padding: 14px 16px;
        text-decoration: none;
      }
  
      li a:hover {
        background-color: #04aa6d;
      }
  
      .active {
        background-color: #333;
      }
    </style>
  </head>
  <body>
    <ul>
      <li><a class="active" href="#home" routerLink="/">Home</a></li>
      <li><a href="#contact" routerLink="/contactus">Contact</a></li>
      <li><a href="#about" routerLink="/aboutus">About</a></li>
    </ul>
  
    <div style="text-align: center; font-weight: bolder; font-size: 50px">
      <router-outlet></router-outlet>
    </div>
  </body>
</html>
                      
                       

Step 3: In this step, we will create three components as home, contact-us, and about-us. For creating these components, we need to run two commands as below mentioned:

ng g component home  ng g component contactUs  ng g component aboutUs

After creating components successfully, we need to create a simple route using both components & simultaneously we need to import all those components to our module file. 

Installation Process

Step 4: We need to import all the required components in the app.module.ts file, after successful installation of those components,

app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
  
import { RouterModule, Router } from '@angular/router';
import { AppRoutingModule } from './app-routing.module';
  
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { ContactUsComponent } from './contact-us/contact-us.component';
import { AboutUsComponent } from './about-us/about-us.component';
  
@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
    ContactUsComponent,
    AboutUsComponent
  ],
  imports: [BrowserModule, FormsModule],
  bootstrap: [AppComponent]
})
export class AppModule {}
                      
                       

Step 5: In this step, we are going to update our routing module file.

app-routing.module.ts

import { NgModule } from "@angular/core";
import { RouterModule, Routes } from "@angular/router";
import { AboutUsComponent } from "./about-us/about-us.component";
import { ContactUsComponent } from "./contact-us/contact-us.component";
import { HomeComponent } from "./home/home.component";
  
const routes: Routes = [
  {
    path: "",
    component: HomeComponent,
  },
  {
    path: "aboutus",
    component: AboutUsComponent,
  },
  {
    path: "contactus",
    component: ContactUsComponent,
  },
];
  
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
})
export class AppRoutingModule {}
                      
                       

Now, let’s run our angular application using the below command:

ng serve
 

Step 6: Creating Nested Routes

In our application, we need two more nested routes for about-us. Now, we need to create two more components for this about-us component. For creating a sub-component for about component, we need to run this below command:

ng g component about-us/ourCompany  ng g component about-us/ourEmployees

Installation Process

Step 7: Updating Routing File

In order to add our newly created components, we need to update our existing app-routing.module.ts file:

app-routing.module.ts

import { NgModule } from "@angular/core";
import { RouterModule, Routes } from "@angular/router";
import { AboutUsComponent } from "./about-us/about-us.component";
import { OurCompanyComponent } from 
    "./about-us/our-company/our-company.component";
import { OurEmployeesComponent } from 
    "./about-us/our-employees/our-employees.component";
import { ContactUsComponent } from "./contact-us/contact-us.component";
import { HomeComponent } from "./home/home.component";
  
const routes: Routes = [
  {
    path: "",
    component: HomeComponent,
  },
  {
    path: "aboutus",
    children: [
      {
        path: "",
        component: AboutUsComponent,
      },
      {
        path: "our_employees",
        component: OurEmployeesComponent,
      },
      {
        path: "our_company",
        component: OurCompanyComponent,
      },
    ],
  },
  {
    path: "contactus",
    component: ContactUsComponent,
  },
];
  
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
})
export class AppRoutingModule {}
                      
                       

Step 8: Now, we need to create two buttons inside our about-us component. So, we need to update files:

about-us.component.html

<p>about-us works!</p>
  
<a class="btn btn-primary" routerLink="/aboutus/our_employees">Our Employees</a>
<br>
<a class="btn btn-primary" routerLink="/aboutus/our_company">Our Company</a>
                      
                       

our-company.component.html

<p>our-company works!</p>
  
<a class="btn btn-primary" routerLink="/aboutus">Back</a>
                      
                       

our-employees.component.html

<p>our-employees works!</p>
  
<a class="btn btn-primary" routerLink="/aboutus">Back</a>
                      
                       

Now, we need to run this angular application using the below command:

ng serve

Output:



Next Article
Routing in Angular JS using Angular UI Router

S

shubhanshuarya007
Improve
Article Tags :
  • AngularJS
  • Web Technologies
  • AngularJS-Questions
  • routing

Similar Reads

  • What is router-outlet in Angular, and where is it used?
    In Angular, a router-outlet is a directive that acts as a placeholder in a component's template. It's used to dynamically load different components based on the current URL route. Router-outlet is a crucial part of Angular's routing system, enabling you to build single-page applications where differ
    5 min read
  • Routing in Angular JS using Angular UI Router
    AngularJS is a front-end web application framework based on JavaScript and is maintained by Google. AngularJS interprets the attributes of HTML as directives to bind input/output components to a model represented by standard JavaScript variables. Pre-requisites: HTML CSS JavaScript AngularJS Angular
    3 min read
  • A Complete Guide To Angular Routing
    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
    6 min read
  • How to execute a routing in the AngularJS framework ?
    In this article, we will learn about how we can perform routing in AngularJS, along with understanding its implementation through the code example.   Routing in AngularJS helps to develop Single Page Applications, which is a web app that loads only a single page, and the part of the page instead of
    7 min read
  • 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
  • What is Angular Router?
    Angular Router is an important feature of the Angular framework that helps you to build rich and interactive single-page applications (SPAs) with multiple views. In this article, we'll learn in detail about Angular Router. PrerequisitesNPM or Node jsBasics of AngularBasics of RoutingCode editor ( e.
    5 min read
  • How to enable routing and navigation between component pages in Angular 8 ?
    The task is to enable routing between angular components by making their routes when a user clicks the link, it will be navigated to page link corresponding to the required component. Let us know what is routing in Angular Angular 8 routing: The Angular 8 Router helps to navigate between pages that
    2 min read
  • What is the role of $routeProvider in AngularJS ?
    In this article, we will see the role of the $routeProvider in AngularJS, along with understanding the basic implementation through the examples. Routing allows us to create Single Page Applications. To do this, we use ng-view and ng-template directives, and $routeProvider services. We use $routePro
    3 min read
  • Mastering React Routing: Learn Navigation and Routing in React Apps
    React Routing is a technique used to handle navigation within a React application. It enables users to move between different views, pages, or components without refreshing the entire page, which is a key feature of Single Page Applications (SPAs). In this article, we will explore the essential conc
    6 min read
  • Angular Exercises, Practice Questions and Solutions
    Are you eager to elevate your web development skills with Angular or seeking to refine your expertise? Immerse yourself in our Angular Exercises, Practice Questions, and Solutions designed for both novices and seasoned developers. Our interactive platform offers engaging coding challenges, progress
    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