SlideShare a Scribd company logo
Understanding
Router State in
Angular 7:
Passing Data
Through
Angular
RouterState




www.bacancytechnology.com
Introduction
Angular application is divided into
Components; those components help divide
the business logic into separate files for
better understanding. While working with
this component-based architecture, it
sometimes happens that one component is
dependent on another component for
further processing so that it passes data
from one component to another.


There are various ways by which we can
pass data from one component to another.
Angular 7.2.0 introduced a new way to pass
data using State Object while navigating
between routed components. The benefit of
using a state object is that you can share
data between routed components with
routeParams without displaying it on the
URL segment, unlike queryParams in
Angular.
Tutorial Goal:
Passing Data
Through
Angular
RouterState
Before developing the demo application,
let’s see what the demo app is about. We
will build a blog application having three
web pages – Home, Categories, and Blog by
Categories. As per our blog title – Passing
data through Angular RouterState, we will
see how to pass data from the Categories
component to the Blog by Categories
component.


Check the below video for the user interface
of the demo app. In the video, check the
console for the data which has been passed
using routerState.
Create
Angular
Application
To create a new angular application, type
the below command:-


ng new my-blog-app
Note– You can name it whatever you want
instead of my-blog-app. We are going to
create a sample blog application here.


Answer the series of questions to create
your project successfully. Make sure that
you choose YES for – Would you like to add
Angular routing? This will create a file app-
routing.module.ts where we will be adding
our project routes.
Configure
Angular
Project
Angular Project Structure
Angular Generate
Components
Generate components for Home, Categories,
and BlogsByCategory for the blog app using
the below commands.


ng g c home
ng g c categories
ng g c blogs-by-category
After running the command, the project
structure will be something like
























Now we’ll create a mock service named
MainService to fetch data for our blog app
by using the below command


ng g service services/main
Now create two files: blog-list.json and
categories.json for mock data and fetch this
data from our main service.


// categories.json
[
{
"id":1,
"name":"App Development"
},
{
"id":2,
"name":"Blockchain Development"
},
{
"id":3,
"name":"Cryptocurrency"
},
]
// blog-list.json
[
{
"title": "How to contribute to Open
Source?",
"description":"Lorem, ipsum dolor sit amet
consectetur adipisicing elit. Sunt ducimus
aliquam nulla nobis quo mollitia rem nisi
dolore alias natus dignissimos dolores eum
aliquid officiis error dolorem, minima
repellat cumque!",
"keywords":"open-source, software,
contribution",
"meta_desc":"lorem, ipsum dolor sit amet
consectetur adipisicing elit. Sunt ducimus
aliquam nulla nobis quo mollitia rem nisi
dolore alias natus dignissimos dolores eum
aliquid officiis error dolorem, minima
repellat cumque!",
"category":"Open Source"
},
{
"title":"Angular Vs React Vs Vue.js",
"description":"Lorem, ipsum dolor sit amet
consectetur adipisicing elit. Sunt ducimus
aliquam nulla nobis quo mollitia rem nisi
dolore alias natus dignissimos dolores eum
aliquid officiis error dolorem, minima
repellat cumque!",
"keywords":"angular, angular.js , react,
react.js , vue, vue.js",
"meta_desc":"lorem, ipsum dolor sit amet
consectetur adipisicing elit. Sunt ducimus
aliquam nulla nobis quo mollitia rem nisi
dolore alias natus dignissimos dolores eum
aliquid officiis error dolorem, minima
repellat cumque!",
"category":"Web Development"
},
{
"title":"Objective C or Swift, What to choose
for iOS development",
"description":"Lorem, ipsum dolor sit amet
consectetur adipisicing elit. Sunt ducimus
aliquam nulla nobis quo mollitia rem nisi
dolore alias natus dignissimos dolores eum
aliquid officiis error dolorem, minima
repellat cumque!",
"keywords":"iPhone, iOS, software, mobile
development",
"meta_desc":"lorem, ipsum dolor sit amet
consectetur adipisicing elit. Sunt ducimus
aliquam nulla nobis quo mollitia rem nisi
dolore alias natus dignissimos dolores eum
aliquid officiis error dolorem, minima
repellat cumque!",
"category":"App Development"
},
]
Now paste the below code into the service
import { HttpClient } from
'@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class MainService {
constructor(private http: HttpClient) { }
getAllCategories() {
return
this.http.get('assets/categories.json');
}
getBlogByCategory(): Observable {
return this.http.get('assets/blog-list.json');
}
}
app-routing.module.ts
home.component.ts
categories.component.ts
categories.component.html
blogs-by-category.component.ts
blogs-by-category.component.html
We’ll be updating the code of these below
files:
Configure
Routes
In this file, we will declare routes with their
respective components. So, the application
would know which component has to be
rendered on which route.


// app-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from
'@angular/router';
import { BlogsByCategoryComponent } from
'./blogs-by-category/blogs-by-
category.component';
import { CategoriesComponent } from
'./categories/categories.component';
const routes: Routes = [
{
// Empty path that will redirect to
categories page.
path: '',
redirectTo: 'home',
pathMatch: 'full'
},
{
// Display home component of the blog
path: 'home',
component: HomeComponent
},
{
// Displays list of blog categories
path: 'categories',
component: CategoriesComponent
},
{
// Displays list of blogs with the selected category
path: 'blogs-by-category',
component: BlogsByCategoryComponent
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
Basic User
Interface
In this section, we will add the below code
for our basic user interface.


// app.component.html
Replace your html file code with the below
code.


<header class="header">
<h1 class="logo"><a routerLink="/">My
Blog</a></h1>
<ul class="main-nav">
<li><a routerLink="/">Home</a></li>
<li><a
routerLink="categories">Categories</a>
</li>
<li><a href="#">Services</a></li>
<li><a href="#">About Us</a></li>
</ul>
</header>
<router-outlet></router-outlet>
// home.component.html
<div class="welcome-text">
<h3>Welcome to my blog please choose a
<em><a
routerLink="/categories">category</a>
</em> for blog content to display.</h3>
</div>
Now let’s move to our core part of the
tutorial: Passing Data Through Angular
RouterState and start transferring data
between the components.
Passing Data
After updating the superficial user
interface, open files related to the
Categories component to update the UI and
write logic to pass data to the Blog by
Categories component.


// categories.component.html
<ul>
<li *ngFor="let category of categories">
<a routerLink="/blogs-by-category"
[state]="category">{{category.name}}</a>
</li>
</ul>
Here, with the help of an attribute directive
[state]=”object”, we will pass data to
another component. This attribute is used
in case you’re relying on declarative
navigation in your app.
// categories.component.ts
import { Component, OnInit } from
'@angular/core';
import { MainService } from
'../services/main.service';
interface Categories {
name: String;
}
@Component({
selector: 'app-categories',
templateUrl: './categories.component.html',
styleUrls: ['./categories.component.css']
})
export class CategoriesComponent
implements OnInit {
public categories: Categories[] = [];
constructor(private mainService:
MainService) { }
ngOnInit(): void {
// Calling the below method to load the
service when component loads.
this.getAllCategories();
}
getAllCategories() {
// We’re subscribing to service to get a list
of categories available.
this.mainService.getAllCategories().subscri
be((listCategories: any) =>
this.categories.push(...listCategories));
}
}
Receiving
Data
Now it’s time to update the user interface
for the Blog by Categories component and
write the logic for receiving data from the
Categories component. Replace your .html
and .ts file with the below code.


// blog-by-categories.component.html


Replace your html file code with the below
code:-


<!-- Here we are looping through each blog
object to display on html -->
<div *ngFor="let blog of blogs">
<h3>{{blog.title}}</h3>
<p>{{blog.description}}</p>
</div>
// blog-by-categories.component.ts
import { Component, OnInit } from
'@angular/core';
import { MainService } from
'../services/main.service';
interface Blog {
title: String;
description: String;
keywords: String;
meta_desc: String;
category: String;
}
@Component({
selector: 'app-blogs-by-category',
templateUrl: './blogs-by-
category.component.html',
styleUrls: ['./blogs-by-
category.component.css']
})
export class BlogsByCategoryComponent
implements OnInit {
public blogs: Blog[] = [];
constructor(private mainService: MainService) {
}
ngOnInit(): void {
const selectedCategory = history.state.name //
Here we got our selected category object and we
access the name of the category using object key.
this.getBlogsByCategory(selectedCategory);
}
getBlogsByCategory(category: string) {
this.mainService.getBlogByCategory()
.subscribe((blogs: Blog[]) => {
this.blogs.push(...blogs.filter(blog =>
blog.category === category)); // Filter based on
selected category.
});
}
}
Github
Repository
You can directly choose to clone the github
repository and play around with the code.
Run the below command to clone the repo
or visit the source code.


git clone https://github.com/aamita96/my-
blog-app.git
Conclusion
I hope the tutorial for passing data through
Angular RouterState was useful for you. For
more such tutorials, visit the Angular
tutorials page and feel free to clone the
github repository. If you are looking for
dedicated developers to manage your
Angular project or build it from scratch,
contact us to hire Angular developer. We
assure you that our skilled developers will
use their problem-solving skills and meet
all your project requirements.
Thank You
www.bacancytechnology.com
Ad

Recommended

Full Angular 7 Firebase Authentication System
Full Angular 7 Firebase Authentication System
Digamber Singh
 
Get rid of controllers in angular 1.5.x start using component directives
Get rid of controllers in angular 1.5.x start using component directives
Marios Fakiolas
 
AngularJS - dependency injection
AngularJS - dependency injection
Alexe Bogdan
 
AngularJS Fundamentals + WebAPI
AngularJS Fundamentals + WebAPI
Eric Wise
 
How To Manage API Request with AXIOS on a React Native App
How To Manage API Request with AXIOS on a React Native App
Andolasoft Inc
 
A Complete Tour of JSF 2
A Complete Tour of JSF 2
Jim Driscoll
 
Angular js
Angular js
Arun Somu Panneerselvam
 
Jsf intro
Jsf intro
vantinhkhuc
 
LearningMVCWithLINQToSQL
LearningMVCWithLINQToSQL
Akhil Mittal
 
Dependency Injection pattern in Angular
Dependency Injection pattern in Angular
Alexe Bogdan
 
Adding User Management to Node.js
Adding User Management to Node.js
Dev_Events
 
Spring 3.x - Spring MVC - Advanced topics
Spring 3.x - Spring MVC - Advanced topics
Guy Nir
 
Spring MVC 3.0 Framework (sesson_2)
Spring MVC 3.0 Framework (sesson_2)
Ravi Kant Soni ([email protected])
 
Spring MVC 3.0 Framework
Spring MVC 3.0 Framework
Ravi Kant Soni ([email protected])
 
Spring Web MVC
Spring Web MVC
zeeshanhanif
 
React render props
React render props
Saikat Samanta
 
Spring MVC Basics
Spring MVC Basics
Bozhidar Bozhanov
 
Angular Data Binding
Angular Data Binding
Jennifer Estrada
 
Introduction to Spring MVC
Introduction to Spring MVC
Richard Paul
 
Angular2 Development for Java developers
Angular2 Development for Java developers
Yakov Fain
 
Intro react js
Intro react js
Vijayakanth MP
 
Angular 8
Angular 8
Sunil OS
 
Comparing Angular and React JS for SPAs
Comparing Angular and React JS for SPAs
Jennifer Estrada
 
Spring MVC
Spring MVC
Emprovise
 
Spring 3.x - Spring MVC
Spring 3.x - Spring MVC
Guy Nir
 
Struts Introduction Course
Struts Introduction Course
guest764934
 
Introduction to React for Frontend Developers
Introduction to React for Frontend Developers
Sergio Nakamura
 
Microsoft identity platform and device authorization flow to use azure servic...
Microsoft identity platform and device authorization flow to use azure servic...
Sunil kumar Mohanty
 
UQ21CA642BA1-Unit-3-WAF-Class18-Introduction to Angular Routing.pptx
UQ21CA642BA1-Unit-3-WAF-Class18-Introduction to Angular Routing.pptx
TamalDey28
 
Angular - Chapter 3 - Components
Angular - Chapter 3 - Components
WebStackAcademy
 

More Related Content

What's hot (20)

LearningMVCWithLINQToSQL
LearningMVCWithLINQToSQL
Akhil Mittal
 
Dependency Injection pattern in Angular
Dependency Injection pattern in Angular
Alexe Bogdan
 
Adding User Management to Node.js
Adding User Management to Node.js
Dev_Events
 
Spring 3.x - Spring MVC - Advanced topics
Spring 3.x - Spring MVC - Advanced topics
Guy Nir
 
Spring MVC 3.0 Framework (sesson_2)
Spring MVC 3.0 Framework (sesson_2)
Ravi Kant Soni ([email protected])
 
Spring MVC 3.0 Framework
Spring MVC 3.0 Framework
Ravi Kant Soni ([email protected])
 
Spring Web MVC
Spring Web MVC
zeeshanhanif
 
React render props
React render props
Saikat Samanta
 
Spring MVC Basics
Spring MVC Basics
Bozhidar Bozhanov
 
Angular Data Binding
Angular Data Binding
Jennifer Estrada
 
Introduction to Spring MVC
Introduction to Spring MVC
Richard Paul
 
Angular2 Development for Java developers
Angular2 Development for Java developers
Yakov Fain
 
Intro react js
Intro react js
Vijayakanth MP
 
Angular 8
Angular 8
Sunil OS
 
Comparing Angular and React JS for SPAs
Comparing Angular and React JS for SPAs
Jennifer Estrada
 
Spring MVC
Spring MVC
Emprovise
 
Spring 3.x - Spring MVC
Spring 3.x - Spring MVC
Guy Nir
 
Struts Introduction Course
Struts Introduction Course
guest764934
 
Introduction to React for Frontend Developers
Introduction to React for Frontend Developers
Sergio Nakamura
 
Microsoft identity platform and device authorization flow to use azure servic...
Microsoft identity platform and device authorization flow to use azure servic...
Sunil kumar Mohanty
 
LearningMVCWithLINQToSQL
LearningMVCWithLINQToSQL
Akhil Mittal
 
Dependency Injection pattern in Angular
Dependency Injection pattern in Angular
Alexe Bogdan
 
Adding User Management to Node.js
Adding User Management to Node.js
Dev_Events
 
Spring 3.x - Spring MVC - Advanced topics
Spring 3.x - Spring MVC - Advanced topics
Guy Nir
 
Introduction to Spring MVC
Introduction to Spring MVC
Richard Paul
 
Angular2 Development for Java developers
Angular2 Development for Java developers
Yakov Fain
 
Angular 8
Angular 8
Sunil OS
 
Comparing Angular and React JS for SPAs
Comparing Angular and React JS for SPAs
Jennifer Estrada
 
Spring 3.x - Spring MVC
Spring 3.x - Spring MVC
Guy Nir
 
Struts Introduction Course
Struts Introduction Course
guest764934
 
Introduction to React for Frontend Developers
Introduction to React for Frontend Developers
Sergio Nakamura
 
Microsoft identity platform and device authorization flow to use azure servic...
Microsoft identity platform and device authorization flow to use azure servic...
Sunil kumar Mohanty
 

Similar to Understanding router state in angular 7 passing data through angular router state (20)

UQ21CA642BA1-Unit-3-WAF-Class18-Introduction to Angular Routing.pptx
UQ21CA642BA1-Unit-3-WAF-Class18-Introduction to Angular Routing.pptx
TamalDey28
 
Angular - Chapter 3 - Components
Angular - Chapter 3 - Components
WebStackAcademy
 
Angular 7 Firebase5 CRUD Operations with Reactive Forms
Angular 7 Firebase5 CRUD Operations with Reactive Forms
Digamber Singh
 
Angular resolver tutorial
Angular resolver tutorial
Katy Slemon
 
Angular Framework ppt for beginners and advanced
Angular Framework ppt for beginners and advanced
Preetha Ganapathi
 
Angular Interview Questions-PDF.pdf
Angular Interview Questions-PDF.pdf
JohnLeo57
 
17612235.ppt
17612235.ppt
yovixi5669
 
Angular Universal How to Build Angular SEO Friendly App.pdf
Angular Universal How to Build Angular SEO Friendly App.pdf
Katy Slemon
 
Angular 4 for Java Developers
Angular 4 for Java Developers
Yakov Fain
 
Data Flow Patterns in Angular 2 - Sebastian Müller
Data Flow Patterns in Angular 2 - Sebastian Müller
Sebastian Holstein
 
Building a TV show with Angular, Bootstrap, and Web Services
Building a TV show with Angular, Bootstrap, and Web Services
David Giard
 
Commit University - Exploring Angular 2
Commit University - Exploring Angular 2
Commit University
 
React JS CONCEPT AND DETAILED EXPLANATION
React JS CONCEPT AND DETAILED EXPLANATION
harshavardhanjuttika
 
Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)
Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)
Ontico
 
mean stack
mean stack
michaelaaron25322
 
Angular2 + rxjs
Angular2 + rxjs
Christoffer Noring
 
Workshop 13: AngularJS Parte II
Workshop 13: AngularJS Parte II
Visual Engineering
 
Angular JS2 Training Session #2
Angular JS2 Training Session #2
Paras Mendiratta
 
StackMob & Appcelerator Module Part One
StackMob & Appcelerator Module Part One
Aaron Saunders
 
Murach : How to work with session state and cookies
Murach : How to work with session state and cookies
MahmoudOHassouna
 
UQ21CA642BA1-Unit-3-WAF-Class18-Introduction to Angular Routing.pptx
UQ21CA642BA1-Unit-3-WAF-Class18-Introduction to Angular Routing.pptx
TamalDey28
 
Angular - Chapter 3 - Components
Angular - Chapter 3 - Components
WebStackAcademy
 
Angular 7 Firebase5 CRUD Operations with Reactive Forms
Angular 7 Firebase5 CRUD Operations with Reactive Forms
Digamber Singh
 
Angular resolver tutorial
Angular resolver tutorial
Katy Slemon
 
Angular Framework ppt for beginners and advanced
Angular Framework ppt for beginners and advanced
Preetha Ganapathi
 
Angular Interview Questions-PDF.pdf
Angular Interview Questions-PDF.pdf
JohnLeo57
 
Angular Universal How to Build Angular SEO Friendly App.pdf
Angular Universal How to Build Angular SEO Friendly App.pdf
Katy Slemon
 
Angular 4 for Java Developers
Angular 4 for Java Developers
Yakov Fain
 
Data Flow Patterns in Angular 2 - Sebastian Müller
Data Flow Patterns in Angular 2 - Sebastian Müller
Sebastian Holstein
 
Building a TV show with Angular, Bootstrap, and Web Services
Building a TV show with Angular, Bootstrap, and Web Services
David Giard
 
Commit University - Exploring Angular 2
Commit University - Exploring Angular 2
Commit University
 
React JS CONCEPT AND DETAILED EXPLANATION
React JS CONCEPT AND DETAILED EXPLANATION
harshavardhanjuttika
 
Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)
Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)
Ontico
 
Workshop 13: AngularJS Parte II
Workshop 13: AngularJS Parte II
Visual Engineering
 
Angular JS2 Training Session #2
Angular JS2 Training Session #2
Paras Mendiratta
 
StackMob & Appcelerator Module Part One
StackMob & Appcelerator Module Part One
Aaron Saunders
 
Murach : How to work with session state and cookies
Murach : How to work with session state and cookies
MahmoudOHassouna
 
Ad

More from Katy Slemon (20)

React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
Katy Slemon
 
Data Science Use Cases in Retail & Healthcare Industries.pdf
Data Science Use Cases in Retail & Healthcare Industries.pdf
Katy Slemon
 
How Much Does It Cost To Hire Golang Developer.pdf
How Much Does It Cost To Hire Golang Developer.pdf
Katy Slemon
 
What’s New in Flutter 3.pdf
What’s New in Flutter 3.pdf
Katy Slemon
 
Why Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdf
Katy Slemon
 
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
Katy Slemon
 
How to Implement Middleware Pipeline in VueJS.pdf
How to Implement Middleware Pipeline in VueJS.pdf
Katy Slemon
 
How to Build Laravel Package Using Composer.pdf
How to Build Laravel Package Using Composer.pdf
Katy Slemon
 
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
Katy Slemon
 
How to Develop Slack Bot Using Golang.pdf
How to Develop Slack Bot Using Golang.pdf
Katy Slemon
 
IoT Based Battery Management System in Electric Vehicles.pdf
IoT Based Battery Management System in Electric Vehicles.pdf
Katy Slemon
 
Understanding Flexbox Layout in React Native.pdf
Understanding Flexbox Layout in React Native.pdf
Katy Slemon
 
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
Katy Slemon
 
New Features in iOS 15 and Swift 5.5.pdf
New Features in iOS 15 and Swift 5.5.pdf
Katy Slemon
 
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
Katy Slemon
 
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
Katy Slemon
 
Flutter Performance Tuning Best Practices From the Pros.pdf
Flutter Performance Tuning Best Practices From the Pros.pdf
Katy Slemon
 
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
Katy Slemon
 
Ruby On Rails Performance Tuning Guide.pdf
Ruby On Rails Performance Tuning Guide.pdf
Katy Slemon
 
Uncovering 04 Main Types and Benefits of Salesforce ISV Partnerships.pdf
Uncovering 04 Main Types and Benefits of Salesforce ISV Partnerships.pdf
Katy Slemon
 
React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
Katy Slemon
 
Data Science Use Cases in Retail & Healthcare Industries.pdf
Data Science Use Cases in Retail & Healthcare Industries.pdf
Katy Slemon
 
How Much Does It Cost To Hire Golang Developer.pdf
How Much Does It Cost To Hire Golang Developer.pdf
Katy Slemon
 
What’s New in Flutter 3.pdf
What’s New in Flutter 3.pdf
Katy Slemon
 
Why Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdf
Katy Slemon
 
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
Katy Slemon
 
How to Implement Middleware Pipeline in VueJS.pdf
How to Implement Middleware Pipeline in VueJS.pdf
Katy Slemon
 
How to Build Laravel Package Using Composer.pdf
How to Build Laravel Package Using Composer.pdf
Katy Slemon
 
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
Katy Slemon
 
How to Develop Slack Bot Using Golang.pdf
How to Develop Slack Bot Using Golang.pdf
Katy Slemon
 
IoT Based Battery Management System in Electric Vehicles.pdf
IoT Based Battery Management System in Electric Vehicles.pdf
Katy Slemon
 
Understanding Flexbox Layout in React Native.pdf
Understanding Flexbox Layout in React Native.pdf
Katy Slemon
 
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
Katy Slemon
 
New Features in iOS 15 and Swift 5.5.pdf
New Features in iOS 15 and Swift 5.5.pdf
Katy Slemon
 
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
Katy Slemon
 
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
Katy Slemon
 
Flutter Performance Tuning Best Practices From the Pros.pdf
Flutter Performance Tuning Best Practices From the Pros.pdf
Katy Slemon
 
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
Katy Slemon
 
Ruby On Rails Performance Tuning Guide.pdf
Ruby On Rails Performance Tuning Guide.pdf
Katy Slemon
 
Uncovering 04 Main Types and Benefits of Salesforce ISV Partnerships.pdf
Uncovering 04 Main Types and Benefits of Salesforce ISV Partnerships.pdf
Katy Slemon
 
Ad

Recently uploaded (20)

Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...
BookNet Canada
 
FIDO Seminar: New Data: Passkey Adoption in the Workforce.pptx
FIDO Seminar: New Data: Passkey Adoption in the Workforce.pptx
FIDO Alliance
 
OpenACC and Open Hackathons Monthly Highlights June 2025
OpenACC and Open Hackathons Monthly Highlights June 2025
OpenACC
 
Security Tips for Enterprise Azure Solutions
Security Tips for Enterprise Azure Solutions
Michele Leroux Bustamante
 
AI vs Human Writing: Can You Tell the Difference?
AI vs Human Writing: Can You Tell the Difference?
Shashi Sathyanarayana, Ph.D
 
Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025
Safe Software
 
Raman Bhaumik - Passionate Tech Enthusiast
Raman Bhaumik - Passionate Tech Enthusiast
Raman Bhaumik
 
AudGram Review: Build Visually Appealing, AI-Enhanced Audiograms to Engage Yo...
AudGram Review: Build Visually Appealing, AI-Enhanced Audiograms to Engage Yo...
SOFTTECHHUB
 
“Key Requirements to Successfully Implement Generative AI in Edge Devices—Opt...
“Key Requirements to Successfully Implement Generative AI in Edge Devices—Opt...
Edge AI and Vision Alliance
 
FIDO Alliance Seminar State of Passkeys.pptx
FIDO Alliance Seminar State of Passkeys.pptx
FIDO Alliance
 
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Safe Software
 
OWASP Barcelona 2025 Threat Model Library
OWASP Barcelona 2025 Threat Model Library
PetraVukmirovic
 
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc
 
FIDO Seminar: Targeting Trust: The Future of Identity in the Workforce.pptx
FIDO Seminar: Targeting Trust: The Future of Identity in the Workforce.pptx
FIDO Alliance
 
MuleSoft for AgentForce : Topic Center and API Catalog
MuleSoft for AgentForce : Topic Center and API Catalog
shyamraj55
 
War_And_Cyber_3_Years_Of_Struggle_And_Lessons_For_Global_Security.pdf
War_And_Cyber_3_Years_Of_Struggle_And_Lessons_For_Global_Security.pdf
biswajitbanerjee38
 
“Why It’s Critical to Have an Integrated Development Methodology for Edge AI,...
“Why It’s Critical to Have an Integrated Development Methodology for Edge AI,...
Edge AI and Vision Alliance
 
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
NTT DATA Technology & Innovation
 
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
Safe Software
 
FIDO Seminar: Perspectives on Passkeys & Consumer Adoption.pptx
FIDO Seminar: Perspectives on Passkeys & Consumer Adoption.pptx
FIDO Alliance
 
Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...
BookNet Canada
 
FIDO Seminar: New Data: Passkey Adoption in the Workforce.pptx
FIDO Seminar: New Data: Passkey Adoption in the Workforce.pptx
FIDO Alliance
 
OpenACC and Open Hackathons Monthly Highlights June 2025
OpenACC and Open Hackathons Monthly Highlights June 2025
OpenACC
 
Security Tips for Enterprise Azure Solutions
Security Tips for Enterprise Azure Solutions
Michele Leroux Bustamante
 
AI vs Human Writing: Can You Tell the Difference?
AI vs Human Writing: Can You Tell the Difference?
Shashi Sathyanarayana, Ph.D
 
Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025
Safe Software
 
Raman Bhaumik - Passionate Tech Enthusiast
Raman Bhaumik - Passionate Tech Enthusiast
Raman Bhaumik
 
AudGram Review: Build Visually Appealing, AI-Enhanced Audiograms to Engage Yo...
AudGram Review: Build Visually Appealing, AI-Enhanced Audiograms to Engage Yo...
SOFTTECHHUB
 
“Key Requirements to Successfully Implement Generative AI in Edge Devices—Opt...
“Key Requirements to Successfully Implement Generative AI in Edge Devices—Opt...
Edge AI and Vision Alliance
 
FIDO Alliance Seminar State of Passkeys.pptx
FIDO Alliance Seminar State of Passkeys.pptx
FIDO Alliance
 
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Safe Software
 
OWASP Barcelona 2025 Threat Model Library
OWASP Barcelona 2025 Threat Model Library
PetraVukmirovic
 
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc
 
FIDO Seminar: Targeting Trust: The Future of Identity in the Workforce.pptx
FIDO Seminar: Targeting Trust: The Future of Identity in the Workforce.pptx
FIDO Alliance
 
MuleSoft for AgentForce : Topic Center and API Catalog
MuleSoft for AgentForce : Topic Center and API Catalog
shyamraj55
 
War_And_Cyber_3_Years_Of_Struggle_And_Lessons_For_Global_Security.pdf
War_And_Cyber_3_Years_Of_Struggle_And_Lessons_For_Global_Security.pdf
biswajitbanerjee38
 
“Why It’s Critical to Have an Integrated Development Methodology for Edge AI,...
“Why It’s Critical to Have an Integrated Development Methodology for Edge AI,...
Edge AI and Vision Alliance
 
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
NTT DATA Technology & Innovation
 
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
Safe Software
 
FIDO Seminar: Perspectives on Passkeys & Consumer Adoption.pptx
FIDO Seminar: Perspectives on Passkeys & Consumer Adoption.pptx
FIDO Alliance
 

Understanding router state in angular 7 passing data through angular router state

  • 1. Understanding Router State in Angular 7: Passing Data Through Angular RouterState www.bacancytechnology.com
  • 3. Angular application is divided into Components; those components help divide the business logic into separate files for better understanding. While working with this component-based architecture, it sometimes happens that one component is dependent on another component for further processing so that it passes data from one component to another. There are various ways by which we can pass data from one component to another. Angular 7.2.0 introduced a new way to pass data using State Object while navigating between routed components. The benefit of using a state object is that you can share data between routed components with routeParams without displaying it on the URL segment, unlike queryParams in Angular.
  • 5. Before developing the demo application, let’s see what the demo app is about. We will build a blog application having three web pages – Home, Categories, and Blog by Categories. As per our blog title – Passing data through Angular RouterState, we will see how to pass data from the Categories component to the Blog by Categories component. Check the below video for the user interface of the demo app. In the video, check the console for the data which has been passed using routerState.
  • 7. To create a new angular application, type the below command:- ng new my-blog-app Note– You can name it whatever you want instead of my-blog-app. We are going to create a sample blog application here. Answer the series of questions to create your project successfully. Make sure that you choose YES for – Would you like to add Angular routing? This will create a file app- routing.module.ts where we will be adding our project routes.
  • 9. Angular Project Structure Angular Generate Components Generate components for Home, Categories, and BlogsByCategory for the blog app using the below commands. ng g c home ng g c categories ng g c blogs-by-category
  • 10. After running the command, the project structure will be something like Now we’ll create a mock service named MainService to fetch data for our blog app by using the below command ng g service services/main
  • 11. Now create two files: blog-list.json and categories.json for mock data and fetch this data from our main service. // categories.json [ { "id":1, "name":"App Development" }, { "id":2, "name":"Blockchain Development" }, { "id":3, "name":"Cryptocurrency" }, ]
  • 12. // blog-list.json [ { "title": "How to contribute to Open Source?", "description":"Lorem, ipsum dolor sit amet consectetur adipisicing elit. Sunt ducimus aliquam nulla nobis quo mollitia rem nisi dolore alias natus dignissimos dolores eum aliquid officiis error dolorem, minima repellat cumque!", "keywords":"open-source, software, contribution", "meta_desc":"lorem, ipsum dolor sit amet consectetur adipisicing elit. Sunt ducimus aliquam nulla nobis quo mollitia rem nisi dolore alias natus dignissimos dolores eum aliquid officiis error dolorem, minima repellat cumque!", "category":"Open Source" },
  • 13. { "title":"Angular Vs React Vs Vue.js", "description":"Lorem, ipsum dolor sit amet consectetur adipisicing elit. Sunt ducimus aliquam nulla nobis quo mollitia rem nisi dolore alias natus dignissimos dolores eum aliquid officiis error dolorem, minima repellat cumque!", "keywords":"angular, angular.js , react, react.js , vue, vue.js", "meta_desc":"lorem, ipsum dolor sit amet consectetur adipisicing elit. Sunt ducimus aliquam nulla nobis quo mollitia rem nisi dolore alias natus dignissimos dolores eum aliquid officiis error dolorem, minima repellat cumque!", "category":"Web Development" }, { "title":"Objective C or Swift, What to choose for iOS development",
  • 14. "description":"Lorem, ipsum dolor sit amet consectetur adipisicing elit. Sunt ducimus aliquam nulla nobis quo mollitia rem nisi dolore alias natus dignissimos dolores eum aliquid officiis error dolorem, minima repellat cumque!", "keywords":"iPhone, iOS, software, mobile development", "meta_desc":"lorem, ipsum dolor sit amet consectetur adipisicing elit. Sunt ducimus aliquam nulla nobis quo mollitia rem nisi dolore alias natus dignissimos dolores eum aliquid officiis error dolorem, minima repellat cumque!", "category":"App Development" }, ] Now paste the below code into the service
  • 15. import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class MainService { constructor(private http: HttpClient) { } getAllCategories() { return this.http.get('assets/categories.json'); } getBlogByCategory(): Observable { return this.http.get('assets/blog-list.json'); } }
  • 18. In this file, we will declare routes with their respective components. So, the application would know which component has to be rendered on which route. // app-routing.module.ts import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { BlogsByCategoryComponent } from './blogs-by-category/blogs-by- category.component'; import { CategoriesComponent } from './categories/categories.component'; const routes: Routes = [ { // Empty path that will redirect to categories page. path: '',
  • 19. redirectTo: 'home', pathMatch: 'full' }, { // Display home component of the blog path: 'home', component: HomeComponent }, { // Displays list of blog categories path: 'categories', component: CategoriesComponent }, { // Displays list of blogs with the selected category path: 'blogs-by-category', component: BlogsByCategoryComponent } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
  • 21. In this section, we will add the below code for our basic user interface. // app.component.html Replace your html file code with the below code. <header class="header"> <h1 class="logo"><a routerLink="/">My Blog</a></h1> <ul class="main-nav"> <li><a routerLink="/">Home</a></li> <li><a routerLink="categories">Categories</a> </li> <li><a href="#">Services</a></li> <li><a href="#">About Us</a></li> </ul> </header> <router-outlet></router-outlet>
  • 22. // home.component.html <div class="welcome-text"> <h3>Welcome to my blog please choose a <em><a routerLink="/categories">category</a> </em> for blog content to display.</h3> </div> Now let’s move to our core part of the tutorial: Passing Data Through Angular RouterState and start transferring data between the components.
  • 24. After updating the superficial user interface, open files related to the Categories component to update the UI and write logic to pass data to the Blog by Categories component. // categories.component.html <ul> <li *ngFor="let category of categories"> <a routerLink="/blogs-by-category" [state]="category">{{category.name}}</a> </li> </ul> Here, with the help of an attribute directive [state]=”object”, we will pass data to another component. This attribute is used in case you’re relying on declarative navigation in your app.
  • 25. // categories.component.ts import { Component, OnInit } from '@angular/core'; import { MainService } from '../services/main.service'; interface Categories { name: String; } @Component({ selector: 'app-categories', templateUrl: './categories.component.html', styleUrls: ['./categories.component.css'] }) export class CategoriesComponent implements OnInit { public categories: Categories[] = []; constructor(private mainService: MainService) { }
  • 26. ngOnInit(): void { // Calling the below method to load the service when component loads. this.getAllCategories(); } getAllCategories() { // We’re subscribing to service to get a list of categories available. this.mainService.getAllCategories().subscri be((listCategories: any) => this.categories.push(...listCategories)); } }
  • 28. Now it’s time to update the user interface for the Blog by Categories component and write the logic for receiving data from the Categories component. Replace your .html and .ts file with the below code. // blog-by-categories.component.html Replace your html file code with the below code:- <!-- Here we are looping through each blog object to display on html --> <div *ngFor="let blog of blogs"> <h3>{{blog.title}}</h3> <p>{{blog.description}}</p> </div>
  • 29. // blog-by-categories.component.ts import { Component, OnInit } from '@angular/core'; import { MainService } from '../services/main.service'; interface Blog { title: String; description: String; keywords: String; meta_desc: String; category: String; } @Component({ selector: 'app-blogs-by-category', templateUrl: './blogs-by- category.component.html', styleUrls: ['./blogs-by- category.component.css'] })
  • 30. export class BlogsByCategoryComponent implements OnInit { public blogs: Blog[] = []; constructor(private mainService: MainService) { } ngOnInit(): void { const selectedCategory = history.state.name // Here we got our selected category object and we access the name of the category using object key. this.getBlogsByCategory(selectedCategory); } getBlogsByCategory(category: string) { this.mainService.getBlogByCategory() .subscribe((blogs: Blog[]) => { this.blogs.push(...blogs.filter(blog => blog.category === category)); // Filter based on selected category. }); } }
  • 32. You can directly choose to clone the github repository and play around with the code. Run the below command to clone the repo or visit the source code. git clone https://github.com/aamita96/my- blog-app.git
  • 34. I hope the tutorial for passing data through Angular RouterState was useful for you. For more such tutorials, visit the Angular tutorials page and feel free to clone the github repository. If you are looking for dedicated developers to manage your Angular project or build it from scratch, contact us to hire Angular developer. We assure you that our skilled developers will use their problem-solving skills and meet all your project requirements.