DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Implementing Micro Frontends in Angular: Step-By-Step Guide
  • Micro Frontends Architecture
  • Difference Between Bootstrap and AngularJS in 2022
  • Login With Google in Angular Firebase Application

Trending

  • A Developer's Guide to Mastering Agentic AI: From Theory to Practice
  • Top Book Picks for Site Reliability Engineers
  • Unlocking the Benefits of a Private API in AWS API Gateway
  • Google Cloud Document AI Basics
  1. DZone
  2. Coding
  3. Frameworks
  4. Angular Routing Between Components (Angular 9)

Angular Routing Between Components (Angular 9)

In this article, we are going to create a new Angular application and add components to implement Routing between the components.

By 
Bhagyashree Nigade user avatar
Bhagyashree Nigade
DZone Core CORE ·
Feb. 17, 21 · Tutorial
Likes (6)
Comment
Save
Tweet
Share
14.2K Views

Join the DZone community and get the full member experience.

Join For Free

Introduction

Angular Routing allows for navigation between components and enables the changing of part of a page, hence the reasoning for developing single page applications. Routing uses the URL in the address bar to change components.

In this article, we are going to create a new Angular application and add components to implement Routing between the components.

Prerequisites

  • Angular CLI
  • NodeJs
  • NPM
  • IDE used—VSCode

Create a New Application/Add Routing To Existing Application

Create a new Application using Angular CLI:

ng new routing-example 

When prompted, select Yes for angular routing. Or use the following command:

ng new routing-example --routing=true

To add routing to an existing application use the following command:

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

 For more information on setup, follow the steps mentioned here.

Adding New Components:

Add a new component using the following command:

ng generate component <component name>

For this demo, we need two components:

  • Languages
  • Info

Adding new components will add the default classes in the component as well. In each component, we at least need the file types of the following: .html, .ts, .css, etc.

Adding Information and Routing:

Once components are added we need to add the route path and components to the app-routing.module.ts:

TypeScript
 




xxxxxxxxxx
1
16


 
1
import { NgModule } from '@angular/core';
2
import { Routes, RouterModule } from '@angular/router';
3
import { InfoComponent } from './info/info.component';
4
import { LanguagesComponent } from './languages/languages.component';
5

          
6
const routes: Routes = [
7
  { path: 'language', component: LanguagesComponent },
8
  { path: 'info', component: InfoComponent },
9
];
10

          
11
@NgModule({
12
  imports: [RouterModule.forRoot(routes)],
13
  exports: [RouterModule]
14
})
15
export class AppRoutingModule { }
16

          


app.component.html:

HTML
 




xxxxxxxxxx
1
10


 
1
<h1>Angular Router App</h1>
2
<!-- This nav gives you links to click, which tells the router which route to use (defined in the routes constant in  AppRoutingModule) -->
3
<nav>
4
  <ul>
5
    <li><a routerLink="/language" routerLinkActive="active">Languages Component</a></li>
6
    <li><a routerLink="/info" routerLinkActive="active">Info Component</a></li>
7
  </ul>
8
</nav>
9
<!-- The routed views render in the <router-outlet>-->
10
<router-outlet></router-outlet>



Add components on the main html page and map them using routerLink. To learn more about RouterLink and ActivatedRoute, click here.

Languages Component

In the languages.component.ts file:

TypeScript
 




x
24


 
1
import { Route } from '@angular/compiler/src/core';
2
import { Component, OnInit } from '@angular/core';
3
import { Router } from '@angular/router';
4

          
5
@Component({
6
  selector: 'app-languages',
7
  templateUrl: './languages.component.html',
8
  styleUrls: ['./languages.component.css']
9
})
10
export class LanguagesComponent implements OnInit {
11
  languages = ['Java', 'Python', 'C', 'C++'];
12
  
13
  constructor(private router: Router) { }
14

          
15
  ngOnInit(): void {
16
  }
17

          
18
  getInfo(selectedLanguage: any) {
19
    console.log(selectedLanguage);
20
    this.router.navigate(['/info', {language: selectedLanguage}]);
21
  }
22

          
23
}



We have created a list of Languages for the drop down. Actual Routing will happen when the getInfo() method is called with the selected language. Once router.navigate is called, the info route will be invoked and the language will be passed along the route.

languages.component.html:

HTML
 




xxxxxxxxxx
1


 
1
<p>Select a Language: </p>
2
<select (change)="getInfo($event.target.value)">
3
    <option>Choose Language</option>
4
    <option *ngFor="let language of languages" value="{{language}}">{{language}}</option>
5
</select>


Info Component

info.component.ts:

TypeScript
 




xxxxxxxxxx
1
34


 
1
import { Component, OnInit } from '@angular/core';
2
import { ActivatedRoute } from "@angular/router";
3

          
4
@Component({
5
  selector: 'app-info',
6
  templateUrl: './info.component.html',
7
  styleUrls: ['./info.component.css']
8
})
9
export class InfoComponent implements OnInit {
10
  selectedLanguage: string;
11
  information: string;
12
  constructor(private route: ActivatedRoute) { }
13

          
14
  ngOnInit(): void {
15
    this.selectedLanguage = this.route.snapshot.paramMap.get("language");
16
    this.getInformation();
17
  }
18

          
19
  getInformation() {
20
    if("Java" == this.selectedLanguage) {
21
      this.information = "Designed by James Gosling, Java is a class based object oriented programming language."
22
    } else if("Python" == this.selectedLanguage) {
23
      this.information = "Python is an interpreted, high-level and general-purpose programming language.";
24
    } else if("C" == this.selectedLanguage) {
25
      this.information = "Designed by Dennis Ritchie, C is a general-purpose, procedural computer programming language.";
26
    } else if("C++" == this.selectedLanguage) {
27
      this.information = "C++ is a general-purpose programming language created by Bjarne Stroustrup as an extension of the C programming language.";
28
    } else {
29
      this.information = "Incorrect selection or no information found for selected language."
30
    }
31
  }
32

          
33
}
34

          



In init, as the component loads, the value passed in router.navigate is assigned to a variable and the information for the selected language is displayed on the screen.

info.component.html:

HTML
 




xxxxxxxxxx
1


 
1
<p>{{information}}</p>



Running the Application

  • To run any Angular application, open the terminal on the IDE or Git Bash command prompt.
  • [Optional]Run command— npm install
  • After the application dependences are up to date, run the application using the command ng serve

Angular Live Development Server up

  • Once the application starts on the default port 4200, run the address from any browser:

Angular Router App

Angular Router App Select Language

Angular Router App Languages and Info component

And you have successfully routed two different angular components! Add and customize the application to build on the model. The code for the above demo is available here.

The browser used for this tutorial is FireFox.

AngularJS application

Opinions expressed by DZone contributors are their own.

Related

  • Implementing Micro Frontends in Angular: Step-By-Step Guide
  • Micro Frontends Architecture
  • Difference Between Bootstrap and AngularJS in 2022
  • Login With Google in Angular Firebase Application

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!