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:
Testing With The Angular HttpClientTestingModule
Next article icon

How to create module with Routing in Angular 9 ?

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

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 components, service providers, and other code files. You can import functions from other NgModules or export a subset of them for use by other NgModules.

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. In this article, we will discuss how to create a module with routing in Angular 9. We will discuss with step-by-step instructions how to create a routing module in an Angular 9 application with a very simple example so that you can easily understand how it works.

We will apply the above approach to build the routing module in a stepwise manner.

  • Create a new Angular Application: Using the following command, we can quickly create an angular app:

    ng new geeksforgeeks-solution
  •  
  • Create the main module: Go inside our project folder. We want to use the Angular CLI command to create a module after we’ve correctly created the app. In an angular application, angular gives a command to construct a module with routing. So, to create the main module, run the command below:

    ng g module main --routing

    After running the successful above command, it will create two files in the new folder name as main inside the app folder.

  • Import-module to module.ts file: We simply import our module into the app.module.ts file, so update this file as shown below:

Approach:

  • Create an Angular app that to be used.
  • Create the navigation links inside the app component and then provide the “routerLink” directive to each route and pass the route value to the “routerLink” directive.
  • Then add the routes to the routing.module.ts file and then import the routing.module.ts into the app.module.ts file.

Project Structure: It will look like the following image:

 

Example:

app.module.ts

import { NgModule } from "@angular/core";
import { BrowserModule } from "@angular/platform-browser";
  
import { AppRoutingModule } from "./app-routing.module";
import { AppComponent } from "./app.component";
import { MainModule } from "./main/main.module";
  
@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, AppRoutingModule, MainModule],
  providers: [],
  bootstrap: [AppComponent],
})
export class AppModule {}
                      
                       

Create components for the main module: We now use the following command to add a new component to our main module, so let’s create the home, about us, and contact us components for the main module:

ng g component main/home  ng g component main/aboutus  ng g component main/contactus

After running the above command successfully:

Add routing for components: In this step we are simply adding the route with the component we created so we need to update our main module routing module file as shown below:

main-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.forChild(routes)],
  exports: [RouterModule],
})
export class MainRoutingModule {}
                      
                       

Update component HTML file: Finally, we need to update the HTML file of our application component, we need to add bindings of all routes with router outlet, so we update them as shown below:

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>
                      
                       

Now, we can run our example application using the below command:

ng serve

Output:

Final Application output



Next Article
Testing With The Angular HttpClientTestingModule

S

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

Similar Reads

  • 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 use Angular MatTabsModule with routing in Angular 17?
    The Angular Material library provides a tab component called MatTabsModule that allows you to organize content into separate tabs. When combined with Angular routing, you can create a seamless navigation experience where each tab loads its content from a different route. In this article, we'll explo
    4 min read
  • Create Project with App Module in Angular 17
    When you try to create the Angular 17 application, you notice that the app.module.ts file is missing. Angular 17 introduces a significant change with Standalone configuration as the default in projects. But if you still want to work with the old folder structure then follow this article to the end.
    6 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
  • Testing With The Angular HttpClientTestingModule
    Testing is an important part of software development, ensuring that your application functions correctly and meets the requirements. Angular provides a powerful module for testing HTTP requests called HttpClientTestingModule. This article will guide you through the process of setting up and using Ht
    2 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 create class in Angular Project?
    In Angular, TypeScript is the primary language for writing code. One of the fundamental concepts in TypeScript is classes, which allow you to define blueprints for creating objects with properties and methods. In this article, we'll explore how to create classes in Angular projects and understand th
    2 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 Get Page Load Time in Angular?
    In web development, performance is the most important thing. Users expect fast and responsive web applications and even minor delays can impact user experience and satisfaction. Monitoring page load time is important for identifying performance bottlenecks and optimizing the user experience. In this
    5 min read
  • How to Get All Route Params/Data in Angular?
    In Angular, managing route parameters and extracting data from routes is important for creating dynamic and responsive web applications. Route parameters allow you to pass information in URLs, and accessing this data enables your application to make decisions and render content dynamically. This art
    4 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