2
Most read
5
Most read
23
Most read
Sharing Data Between
Angular Components
Akhil K • 28.03.2019
Overview
Basic concepts of Angular
● Components and Services
● Binding and Interpolation
● How to load components
● Using directives
Sharing data between components
● Parent to child
● Child to parent
● Unrelated components
Components and Services
Components
● A component is just a class that
serves as a controller for the user
interface.
● It consists of three parts - some
TypeScript code, an HTML template,
and CSS styles.
Services
● You can use services to organize and
share code and data across your
app.
Examples
import { Component} from '@angular/core';
@Component({
selector: 'some-component,
templateUrl: 'some-component.html',
styleUrls: ['some-component.css'],
})
export class SomeComponent {
}
import { Injectable } from
'@angular/core';
@Injectable()
export class SomeService {
}
Binding and Interpolation
Binding
● Binding is just a way to connect data
from the TypeScript code to the
HTML.
● We can bind to attributes using
square brackets [ ]. We can also bind
to events using ( ) parenthesis.
Interpolation
● Interpolation refers to embedding
expressions into marked up text.
● We can also interpolate values from
the TypeScript using handlebars
syntax.
Examples
@Component(...)
export class SomeComponent {
clicked = false;
handleClick() {
this.clicked = true;
}
}
<button [disabled]="clicked"
(click)="handleClick()"></button>
@Component(...)
export class SomeComponent {
appName = 'Cool App';
}
<h1>{{ appName }}</h1>
How to load components
● Declare the components in the
HTML.
● Example:
○ <app-cool></app-cool>
● Load the component with the router.
This tells Angular to imperatively
load the component when you
navigate to http://localhost:4200/cool.
● Example:
○ const routes: Routes = [{
path: 'cool',
component: CoolComponent
}];
Using directives
● *ngIf - Renders some HTML if the
condition is true.
● *ngFor - Repeats elements by
looping over an array of data.
● ngClass - Applies CSS class
conditionally.
● ngStyle - Applies styles conditionally.
● <div *ngIf="clicked">Clicked!</div>
● <div *ngFor="let boat of boats">
{{ boat.name }}
</div>
● <h3 [ngClass]="{
'green': boat.name === 'Starfire',
'red' : boat.name === 'Oracle'
}">
● <h3 [ngStyle]="{
'color': true ? 'red' : 'green'
}">
Sharing Data Between
Components
Parent to Child: Sharing data via Input
● This is probably the most common and straightforward method of sharing data.
● It works by using the @Input() decorator to allow data to be passed via the template.
Examples
parent.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-parent',
template: `<app-child
[childMessage]="parentMessage"></app-child>`,
styleUrls: ['./parent.component.css']
})
export class ParentComponent{
parentMessage = "message from parent"
constructor() { }
}
child.component.ts
import { Component, Input } from
'@angular/core';
@Component({
selector: 'app-child',
template: `Say {{ message }}`,
styleUrls: ['./child.component.css']
})
export class ChildComponent {
@Input() childMessage: string;
constructor() { }
}
Child to Parent: Sharing data via ViewChild
● ViewChild allows one component to be injected into another, giving the parent access
to its attributes and functions.
● However, is that child won’t be available until after the view has been initialized. This
means we need to implement the AfterViewInit lifecycle hook to receive the data from
the child.
parent.component.ts
import { Component, ViewChild, AfterViewInit } from '@angular/core';
import { ChildComponent } from "../child/child.component";
@Component({
selector: 'app-parent',
template: `Message: {{ message }}<app-child></app-child>`,
styleUrls: ['./parent.component.css']
})
export class ParentComponent implements AfterViewInit {
@ViewChild(ChildComponent) child;
constructor() { }
message:string;
ngAfterViewInit() {
this.message = this.child.message
}}}
child.component.ts
import { Component} from '@angular/core';
@Component({
selector: 'app-child',
template: ``,
styleUrls: ['./child.component.css']
})
export class ChildComponent {
message = 'Hello!';
constructor() { }
}
Child to Parent: Sharing data via Output
● Another way to share data is to emit data from the child, which can be listed by the
parent.
● This approach is ideal when you want to share data changes that occur on things like
button clicks and other user events.
● In the parent, we create a function to receive the message and set it equal to the
message variable.
parent.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-parent',
template: `Message: {{message}}
<app-child (messageEvent)="receiveMessage($event)"></app-child>`,
styleUrls: ['./parent.component.css']
})
export class ParentComponent {
constructor() { }
message:string;
receiveMessage($event) {
this.message = $event
}
}
child.component.ts
import { Component, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-child',
template: `<button (click)="sendMessage()">Send Message</button>`,
styleUrls: ['./child.component.css']
})
export class ChildComponent {
message: string = "Hello!"
@Output() messageEvent = new EventEmitter<string>();
constructor() { }
sendMessage() {
this.messageEvent.emit(this.message)
}
}
Unrelated Components: Sharing data
with a Service
● When passing data between components that lack direct connection, such as
siblings ets., you should have a shared service.
● When you have data that should always be shared then RxJs Subject is useful in this
situation.
● The parent, child sibling components all receive the same treatment.
data.service.ts
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable()
export class DataService {
private messageSource = new BehaviorSubject(null);
currentMessage = this.messageSource.asObservable();
constructor() { }
changeMessage(message: string) {
this.messageSource.next(message)
}
}
parent.component.ts
import { Component, OnInit } from '@angular/core';
import { DataService } from "../data.service";
@Component({
selector: 'app-parent',
template: `{{message}}`,
styleUrls: ['./sibling.component.css']
})
export class ParentComponent implements OnInit {
message:string;
constructor(private data: DataService) { }
ngOnInit() {
this.data.currentMessage.subscribe(message => this.message = message)
}
}
sibling.component.ts
import { Component, OnInit } from '@angular/core';
import { DataService } from "../data.service";
@Component({
selector: 'app-sibling',
template: `{{message}}<button (click)="newMessage()">New Message</button>`,
styleUrls: ['./sibling.component.css']
})
export class SiblingComponent implements OnInit {
message:string;
constructor(private data: DataService) { }
ngOnInit() {
this.data.currentMessage.subscribe(message => this.message = message)
}
newMessage() { this.data.changeMessage("Hello from Sibling") }
}
Queries ?
Thanks

More Related Content

PPTX
Introduction to angular with a simple but complete project
PDF
Observables in Angular
PDF
Introduction to RxJS
ODP
Introduction to PostgreSQL
PDF
Kubernetes Basics
PPTX
An introduction to OAuth 2
PDF
Hibernate Presentation
PPS
JUnit Presentation
Introduction to angular with a simple but complete project
Observables in Angular
Introduction to RxJS
Introduction to PostgreSQL
Kubernetes Basics
An introduction to OAuth 2
Hibernate Presentation
JUnit Presentation

What's hot (20)

PDF
Angular - Chapter 7 - HTTP Services
PDF
Angular Advanced Routing
PPTX
Angular 9
PDF
Angular data binding
PDF
Angular - Chapter 1 - Introduction
PPTX
Angular Data Binding
PPTX
Angular modules in depth
PPTX
ODP
Routing & Navigating Pages in Angular 2
PPT
Angular Introduction By Surekha Gadkari
PPTX
PPTX
React js programming concept
PDF
Introduction to React JS
PDF
Angular - Chapter 4 - Data and Event Handling
PDF
Angular - Chapter 3 - Components
PDF
React JS - Introduction
PPTX
Angular Data Binding
PPTX
Angular tutorial
PPTX
Unit 1 - TypeScript & Introduction to Angular CLI.pptx
PPTX
Angular overview
Angular - Chapter 7 - HTTP Services
Angular Advanced Routing
Angular 9
Angular data binding
Angular - Chapter 1 - Introduction
Angular Data Binding
Angular modules in depth
Routing & Navigating Pages in Angular 2
Angular Introduction By Surekha Gadkari
React js programming concept
Introduction to React JS
Angular - Chapter 4 - Data and Event Handling
Angular - Chapter 3 - Components
React JS - Introduction
Angular Data Binding
Angular tutorial
Unit 1 - TypeScript & Introduction to Angular CLI.pptx
Angular overview
Ad

Similar to Sharing Data Between Angular Components (20)

PPTX
passDataB_wComponentInAngular.pptx
PDF
Angular JS2 Training Session #2
PDF
Capstone ms2
PDF
Angular 2 - The Next Framework
PDF
Angular 2 binding
PDF
Web components with Angular
PPTX
Angular Framework ppt for beginners and advanced
PPTX
Fly High With Angular - How to build an app using Angular
PPTX
angular-concepts-introduction-slides.pptx
PPTX
Angular Directives
PDF
Understanding router state in angular 7 passing data through angular router s...
PDF
[FEConf Korea 2017]Angular 컴포넌트 대화법
PPTX
Frontend training
PPTX
Angular2 + rxjs
PPTX
mean stack
PDF
better-apps-angular-2-day1.pdf and home
PPTX
Data Sharing Between Child and Parent Components in AngularJS
PPTX
Building a TV show with Angular, Bootstrap, and Web Services
PDF
Angular 2 Upgrade: Migration von AngularJS 1.x zu 2.0
PPTX
Angular 2 in-1
passDataB_wComponentInAngular.pptx
Angular JS2 Training Session #2
Capstone ms2
Angular 2 - The Next Framework
Angular 2 binding
Web components with Angular
Angular Framework ppt for beginners and advanced
Fly High With Angular - How to build an app using Angular
angular-concepts-introduction-slides.pptx
Angular Directives
Understanding router state in angular 7 passing data through angular router s...
[FEConf Korea 2017]Angular 컴포넌트 대화법
Frontend training
Angular2 + rxjs
mean stack
better-apps-angular-2-day1.pdf and home
Data Sharing Between Child and Parent Components in AngularJS
Building a TV show with Angular, Bootstrap, and Web Services
Angular 2 Upgrade: Migration von AngularJS 1.x zu 2.0
Angular 2 in-1
Ad

More from Squash Apps Pvt Ltd (15)

PPTX
The Critical role of Copyright
PPTX
Please review and merge
PPTX
Angular Lifecycle Hooks
PPTX
Next Generation of Javascript
PPTX
Hybrid app development frameworks
PPTX
API Gateway with legend lambada
PPTX
Life Cycle hooks in VueJs
PPTX
An Intro into webpack
PPTX
Lets vue(view) Vuex from the Top Vue(View)
PPTX
An Overview on Nuxt.js
PPTX
AWS Jungle - Lambda
PPTX
Angular Lazy Loading and Resolve (Route Resolver)
PPTX
Basics of NGINX
ODP
Basics of VueJS
The Critical role of Copyright
Please review and merge
Angular Lifecycle Hooks
Next Generation of Javascript
Hybrid app development frameworks
API Gateway with legend lambada
Life Cycle hooks in VueJs
An Intro into webpack
Lets vue(view) Vuex from the Top Vue(View)
An Overview on Nuxt.js
AWS Jungle - Lambda
Angular Lazy Loading and Resolve (Route Resolver)
Basics of NGINX
Basics of VueJS

Recently uploaded (20)

PPTX
AI-driven Assurance Across Your End-to-end Network With ThousandEyes
PPTX
How to Convert Tickets Into Sales Opportunity in Odoo 18
PPTX
Report in SIP_Distance_Learning_Technology_Impact.pptx
PDF
giants, standing on the shoulders of - by Daniel Stenberg
PDF
Introduction to MCP and A2A Protocols: Enabling Agent Communication
PDF
EIS-Webinar-Regulated-Industries-2025-08.pdf
PDF
CCUS-as-the-Missing-Link-to-Net-Zero_AksCurious.pdf
PPTX
Information-Technology-in-Human-Society.pptx
PDF
SaaS reusability assessment using machine learning techniques
PDF
Transform-Quality-Engineering-with-AI-A-60-Day-Blueprint-for-Digital-Success.pdf
PPTX
Blending method and technology for hydrogen.pptx
PDF
The-Future-of-Automotive-Quality-is-Here-AI-Driven-Engineering.pdf
PDF
NewMind AI Journal Monthly Chronicles - August 2025
PDF
Streamline Vulnerability Management From Minimal Images to SBOMs
PDF
Build Real-Time ML Apps with Python, Feast & NoSQL
PDF
Identification of potential depression in social media posts
PPTX
Presentation - Principles of Instructional Design.pptx
PDF
Transform-Your-Streaming-Platform-with-AI-Driven-Quality-Engineering.pdf
PDF
Rapid Prototyping: A lecture on prototyping techniques for interface design
PPTX
Rise of the Digital Control Grid Zeee Media and Hope and Tivon FTWProject.com
AI-driven Assurance Across Your End-to-end Network With ThousandEyes
How to Convert Tickets Into Sales Opportunity in Odoo 18
Report in SIP_Distance_Learning_Technology_Impact.pptx
giants, standing on the shoulders of - by Daniel Stenberg
Introduction to MCP and A2A Protocols: Enabling Agent Communication
EIS-Webinar-Regulated-Industries-2025-08.pdf
CCUS-as-the-Missing-Link-to-Net-Zero_AksCurious.pdf
Information-Technology-in-Human-Society.pptx
SaaS reusability assessment using machine learning techniques
Transform-Quality-Engineering-with-AI-A-60-Day-Blueprint-for-Digital-Success.pdf
Blending method and technology for hydrogen.pptx
The-Future-of-Automotive-Quality-is-Here-AI-Driven-Engineering.pdf
NewMind AI Journal Monthly Chronicles - August 2025
Streamline Vulnerability Management From Minimal Images to SBOMs
Build Real-Time ML Apps with Python, Feast & NoSQL
Identification of potential depression in social media posts
Presentation - Principles of Instructional Design.pptx
Transform-Your-Streaming-Platform-with-AI-Driven-Quality-Engineering.pdf
Rapid Prototyping: A lecture on prototyping techniques for interface design
Rise of the Digital Control Grid Zeee Media and Hope and Tivon FTWProject.com

Sharing Data Between Angular Components

  • 1. Sharing Data Between Angular Components Akhil K • 28.03.2019
  • 2. Overview Basic concepts of Angular ● Components and Services ● Binding and Interpolation ● How to load components ● Using directives Sharing data between components ● Parent to child ● Child to parent ● Unrelated components
  • 3. Components and Services Components ● A component is just a class that serves as a controller for the user interface. ● It consists of three parts - some TypeScript code, an HTML template, and CSS styles. Services ● You can use services to organize and share code and data across your app.
  • 4. Examples import { Component} from '@angular/core'; @Component({ selector: 'some-component, templateUrl: 'some-component.html', styleUrls: ['some-component.css'], }) export class SomeComponent { } import { Injectable } from '@angular/core'; @Injectable() export class SomeService { }
  • 5. Binding and Interpolation Binding ● Binding is just a way to connect data from the TypeScript code to the HTML. ● We can bind to attributes using square brackets [ ]. We can also bind to events using ( ) parenthesis. Interpolation ● Interpolation refers to embedding expressions into marked up text. ● We can also interpolate values from the TypeScript using handlebars syntax.
  • 6. Examples @Component(...) export class SomeComponent { clicked = false; handleClick() { this.clicked = true; } } <button [disabled]="clicked" (click)="handleClick()"></button> @Component(...) export class SomeComponent { appName = 'Cool App'; } <h1>{{ appName }}</h1>
  • 7. How to load components ● Declare the components in the HTML. ● Example: ○ <app-cool></app-cool> ● Load the component with the router. This tells Angular to imperatively load the component when you navigate to http://localhost:4200/cool. ● Example: ○ const routes: Routes = [{ path: 'cool', component: CoolComponent }];
  • 8. Using directives ● *ngIf - Renders some HTML if the condition is true. ● *ngFor - Repeats elements by looping over an array of data. ● ngClass - Applies CSS class conditionally. ● ngStyle - Applies styles conditionally. ● <div *ngIf="clicked">Clicked!</div> ● <div *ngFor="let boat of boats"> {{ boat.name }} </div> ● <h3 [ngClass]="{ 'green': boat.name === 'Starfire', 'red' : boat.name === 'Oracle' }"> ● <h3 [ngStyle]="{ 'color': true ? 'red' : 'green' }">
  • 10. Parent to Child: Sharing data via Input ● This is probably the most common and straightforward method of sharing data. ● It works by using the @Input() decorator to allow data to be passed via the template.
  • 11. Examples parent.component.ts import { Component } from '@angular/core'; @Component({ selector: 'app-parent', template: `<app-child [childMessage]="parentMessage"></app-child>`, styleUrls: ['./parent.component.css'] }) export class ParentComponent{ parentMessage = "message from parent" constructor() { } } child.component.ts import { Component, Input } from '@angular/core'; @Component({ selector: 'app-child', template: `Say {{ message }}`, styleUrls: ['./child.component.css'] }) export class ChildComponent { @Input() childMessage: string; constructor() { } }
  • 12. Child to Parent: Sharing data via ViewChild ● ViewChild allows one component to be injected into another, giving the parent access to its attributes and functions. ● However, is that child won’t be available until after the view has been initialized. This means we need to implement the AfterViewInit lifecycle hook to receive the data from the child.
  • 13. parent.component.ts import { Component, ViewChild, AfterViewInit } from '@angular/core'; import { ChildComponent } from "../child/child.component"; @Component({ selector: 'app-parent', template: `Message: {{ message }}<app-child></app-child>`, styleUrls: ['./parent.component.css'] }) export class ParentComponent implements AfterViewInit { @ViewChild(ChildComponent) child; constructor() { } message:string; ngAfterViewInit() { this.message = this.child.message }}}
  • 14. child.component.ts import { Component} from '@angular/core'; @Component({ selector: 'app-child', template: ``, styleUrls: ['./child.component.css'] }) export class ChildComponent { message = 'Hello!'; constructor() { } }
  • 15. Child to Parent: Sharing data via Output ● Another way to share data is to emit data from the child, which can be listed by the parent. ● This approach is ideal when you want to share data changes that occur on things like button clicks and other user events. ● In the parent, we create a function to receive the message and set it equal to the message variable.
  • 16. parent.component.ts import { Component } from '@angular/core'; @Component({ selector: 'app-parent', template: `Message: {{message}} <app-child (messageEvent)="receiveMessage($event)"></app-child>`, styleUrls: ['./parent.component.css'] }) export class ParentComponent { constructor() { } message:string; receiveMessage($event) { this.message = $event } }
  • 17. child.component.ts import { Component, Output, EventEmitter } from '@angular/core'; @Component({ selector: 'app-child', template: `<button (click)="sendMessage()">Send Message</button>`, styleUrls: ['./child.component.css'] }) export class ChildComponent { message: string = "Hello!" @Output() messageEvent = new EventEmitter<string>(); constructor() { } sendMessage() { this.messageEvent.emit(this.message) } }
  • 18. Unrelated Components: Sharing data with a Service ● When passing data between components that lack direct connection, such as siblings ets., you should have a shared service. ● When you have data that should always be shared then RxJs Subject is useful in this situation. ● The parent, child sibling components all receive the same treatment.
  • 19. data.service.ts import { Injectable } from '@angular/core'; import { BehaviorSubject } from 'rxjs'; @Injectable() export class DataService { private messageSource = new BehaviorSubject(null); currentMessage = this.messageSource.asObservable(); constructor() { } changeMessage(message: string) { this.messageSource.next(message) } }
  • 20. parent.component.ts import { Component, OnInit } from '@angular/core'; import { DataService } from "../data.service"; @Component({ selector: 'app-parent', template: `{{message}}`, styleUrls: ['./sibling.component.css'] }) export class ParentComponent implements OnInit { message:string; constructor(private data: DataService) { } ngOnInit() { this.data.currentMessage.subscribe(message => this.message = message) } }
  • 21. sibling.component.ts import { Component, OnInit } from '@angular/core'; import { DataService } from "../data.service"; @Component({ selector: 'app-sibling', template: `{{message}}<button (click)="newMessage()">New Message</button>`, styleUrls: ['./sibling.component.css'] }) export class SiblingComponent implements OnInit { message:string; constructor(private data: DataService) { } ngOnInit() { this.data.currentMessage.subscribe(message => this.message = message) } newMessage() { this.data.changeMessage("Hello from Sibling") } }