SlideShare a Scribd company logo
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

PDF
Observables in Angular
Knoldus Inc.
Ā 
PPTX
Angular Data Binding
Jennifer Estrada
Ā 
PPTX
Introduction to angular with a simple but complete project
Jadson Santos
Ā 
PPTX
Azure dev ops
Swaminathan Vetri
Ā 
PPTX
Introduction to Docker - 2017
Docker, Inc.
Ā 
PPT
Angular Introduction By Surekha Gadkari
Surekha Gadkari
Ā 
PPTX
Python - An Introduction
Swarit Wadhe
Ā 
PPTX
Angular modules in depth
Christoffer Noring
Ā 
Observables in Angular
Knoldus Inc.
Ā 
Angular Data Binding
Jennifer Estrada
Ā 
Introduction to angular with a simple but complete project
Jadson Santos
Ā 
Azure dev ops
Swaminathan Vetri
Ā 
Introduction to Docker - 2017
Docker, Inc.
Ā 
Angular Introduction By Surekha Gadkari
Surekha Gadkari
Ā 
Python - An Introduction
Swarit Wadhe
Ā 
Angular modules in depth
Christoffer Noring
Ā 

What's hot (20)

PPTX
Angular 2.0 forms
Eyal Vardi
Ā 
PDF
Angular - Chapter 7 - HTTP Services
WebStackAcademy
Ā 
PDF
Angular - Chapter 3 - Components
WebStackAcademy
Ā 
PPTX
Angular overview
Thanvilahari
Ā 
PDF
Angular Directives
iFour Technolab Pvt. Ltd.
Ā 
PPTX
Angular tutorial
Rohit Gupta
Ā 
PPTX
Angular 9
Raja Vishnu
Ā 
PDF
The New JavaScript: ES6
Rob Eisenberg
Ā 
PPTX
Angular introduction students
Christian John Felix
Ā 
PPTX
Angular Directives
Malla Reddy University
Ā 
PDF
Angular - Chapter 4 - Data and Event Handling
WebStackAcademy
Ā 
PDF
Angular data binding
Sultan Ahmed
Ā 
PPTX
Angular Data Binding
Duy Khanh
Ā 
PPT
Angular 8
Sunil OS
Ā 
PPTX
Meetup angular http client
Gaurav Madaan
Ā 
PDF
ES6 presentation
ritika1
Ā 
PDF
Angular Pipes Workshop
Nir Kaufman
Ā 
PDF
Angular routing
Sultan Ahmed
Ā 
PPTX
Angular 14.pptx
MohaNedGhawar
Ā 
ODP
Routing & Navigating Pages in Angular 2
Knoldus Inc.
Ā 
Angular 2.0 forms
Eyal Vardi
Ā 
Angular - Chapter 7 - HTTP Services
WebStackAcademy
Ā 
Angular - Chapter 3 - Components
WebStackAcademy
Ā 
Angular overview
Thanvilahari
Ā 
Angular Directives
iFour Technolab Pvt. Ltd.
Ā 
Angular tutorial
Rohit Gupta
Ā 
Angular 9
Raja Vishnu
Ā 
The New JavaScript: ES6
Rob Eisenberg
Ā 
Angular introduction students
Christian John Felix
Ā 
Angular Directives
Malla Reddy University
Ā 
Angular - Chapter 4 - Data and Event Handling
WebStackAcademy
Ā 
Angular data binding
Sultan Ahmed
Ā 
Angular Data Binding
Duy Khanh
Ā 
Angular 8
Sunil OS
Ā 
Meetup angular http client
Gaurav Madaan
Ā 
ES6 presentation
ritika1
Ā 
Angular Pipes Workshop
Nir Kaufman
Ā 
Angular routing
Sultan Ahmed
Ā 
Angular 14.pptx
MohaNedGhawar
Ā 
Routing & Navigating Pages in Angular 2
Knoldus Inc.
Ā 
Ad

Similar to Sharing Data Between Angular Components (20)

PPTX
passDataB_wComponentInAngular.pptx
MohitUpadhyay67
Ā 
PDF
Angular JS2 Training Session #2
Paras Mendiratta
Ā 
PDF
Capstone ms2
TanishGupta44
Ā 
PDF
Angular 2 - The Next Framework
Commit University
Ā 
PDF
Angular 2 binding
Nathan Krasney
Ā 
PDF
Web components with Angular
Ana Cidre
Ā 
PPTX
Angular Framework ppt for beginners and advanced
Preetha Ganapathi
Ā 
PPTX
Fly High With Angular - How to build an app using Angular
Vacation Labs
Ā 
PPTX
angular-concepts-introduction-slides.pptx
shekharmpatil1309
Ā 
PDF
Understanding router state in angular 7 passing data through angular router s...
Katy Slemon
Ā 
PDF
[FEConf Korea 2017]Angular į„į…„į†·į„‘į…©į„‚į…„į†«į„į…³ į„ƒį…¢į„’į…Ŗį„‡į…„į†ø
Jeado Ko
Ā 
PPTX
Frontend training
Adrian Caetano
Ā 
PPTX
Angular2 + rxjs
Christoffer Noring
Ā 
PPTX
mean stack
michaelaaron25322
Ā 
PDF
better-apps-angular-2-day1.pdf and home
ChethanGowda886434
Ā 
PPTX
Data Sharing Between Child and Parent Components in AngularJS
Fibonalabs
Ā 
PPTX
Building a TV show with Angular, Bootstrap, and Web Services
David Giard
Ā 
PDF
Angular 2 Upgrade: Migration von AngularJS 1.x zu 2.0
Manfred Steyer
Ā 
PPTX
Angular 2 in-1
GlobalLogic Ukraine
Ā 
PDF
Exploring Angular 2 - Episode 1
Ahmed Moawad
Ā 
passDataB_wComponentInAngular.pptx
MohitUpadhyay67
Ā 
Angular JS2 Training Session #2
Paras Mendiratta
Ā 
Capstone ms2
TanishGupta44
Ā 
Angular 2 - The Next Framework
Commit University
Ā 
Angular 2 binding
Nathan Krasney
Ā 
Web components with Angular
Ana Cidre
Ā 
Angular Framework ppt for beginners and advanced
Preetha Ganapathi
Ā 
Fly High With Angular - How to build an app using Angular
Vacation Labs
Ā 
angular-concepts-introduction-slides.pptx
shekharmpatil1309
Ā 
Understanding router state in angular 7 passing data through angular router s...
Katy Slemon
Ā 
[FEConf Korea 2017]Angular į„į…„į†·į„‘į…©į„‚į…„į†«į„į…³ į„ƒį…¢į„’į…Ŗį„‡į…„į†ø
Jeado Ko
Ā 
Frontend training
Adrian Caetano
Ā 
Angular2 + rxjs
Christoffer Noring
Ā 
mean stack
michaelaaron25322
Ā 
better-apps-angular-2-day1.pdf and home
ChethanGowda886434
Ā 
Data Sharing Between Child and Parent Components in AngularJS
Fibonalabs
Ā 
Building a TV show with Angular, Bootstrap, and Web Services
David Giard
Ā 
Angular 2 Upgrade: Migration von AngularJS 1.x zu 2.0
Manfred Steyer
Ā 
Angular 2 in-1
GlobalLogic Ukraine
Ā 
Exploring Angular 2 - Episode 1
Ahmed Moawad
Ā 
Ad

More from Squash Apps Pvt Ltd (15)

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

Recently uploaded (20)

PDF
Doc9.....................................
SofiaCollazos
Ā 
PPTX
ChatGPT's Deck on The Enduring Legacy of Fax Machines
Greg Swan
Ā 
PDF
Software Development Methodologies in 2025
KodekX
Ā 
PDF
Cloud-Migration-Best-Practices-A-Practical-Guide-to-AWS-Azure-and-Google-Clou...
Artjoker Software Development Company
Ā 
PDF
SparkLabs Primer on Artificial Intelligence 2025
SparkLabs Group
Ā 
PPTX
OA presentation.pptx OA presentation.pptx
pateldhruv002338
Ā 
PDF
REPORT: Heating appliances market in Poland 2024
SPIUG
Ā 
PDF
Chapter 2 Digital Image Fundamentals.pdf
Getnet Tigabie Askale -(GM)
Ā 
PDF
Structs to JSON: How Go Powers REST APIs
Emily Achieng
Ā 
PDF
Building High-Performance Oracle Teams: Strategic Staffing for Database Manag...
SMACT Works
Ā 
PDF
CIFDAQ'S Market Insight: BTC to ETH money in motion
CIFDAQ
Ā 
PDF
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
Ā 
PPTX
How to Build a Scalable Micro-Investing Platform in 2025 - A Founder’s Guide ...
Third Rock Techkno
Ā 
PPT
L2 Rules of Netiquette in Empowerment technology
Archibal2
Ā 
PDF
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
Ā 
PDF
Data_Analytics_vs_Data_Science_vs_BI_by_CA_Suvidha_Chaplot.pdf
CA Suvidha Chaplot
Ā 
PDF
Unlocking the Future- AI Agents Meet Oracle Database 23ai - AIOUG Yatra 2025.pdf
Sandesh Rao
Ā 
PDF
Tea4chat - another LLM Project by Kerem Atam
a0m0rajab1
Ā 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
Ā 
PDF
How-Cloud-Computing-Impacts-Businesses-in-2025-and-Beyond.pdf
Artjoker Software Development Company
Ā 
Doc9.....................................
SofiaCollazos
Ā 
ChatGPT's Deck on The Enduring Legacy of Fax Machines
Greg Swan
Ā 
Software Development Methodologies in 2025
KodekX
Ā 
Cloud-Migration-Best-Practices-A-Practical-Guide-to-AWS-Azure-and-Google-Clou...
Artjoker Software Development Company
Ā 
SparkLabs Primer on Artificial Intelligence 2025
SparkLabs Group
Ā 
OA presentation.pptx OA presentation.pptx
pateldhruv002338
Ā 
REPORT: Heating appliances market in Poland 2024
SPIUG
Ā 
Chapter 2 Digital Image Fundamentals.pdf
Getnet Tigabie Askale -(GM)
Ā 
Structs to JSON: How Go Powers REST APIs
Emily Achieng
Ā 
Building High-Performance Oracle Teams: Strategic Staffing for Database Manag...
SMACT Works
Ā 
CIFDAQ'S Market Insight: BTC to ETH money in motion
CIFDAQ
Ā 
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
Ā 
How to Build a Scalable Micro-Investing Platform in 2025 - A Founder’s Guide ...
Third Rock Techkno
Ā 
L2 Rules of Netiquette in Empowerment technology
Archibal2
Ā 
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
Ā 
Data_Analytics_vs_Data_Science_vs_BI_by_CA_Suvidha_Chaplot.pdf
CA Suvidha Chaplot
Ā 
Unlocking the Future- AI Agents Meet Oracle Database 23ai - AIOUG Yatra 2025.pdf
Sandesh Rao
Ā 
Tea4chat - another LLM Project by Kerem Atam
a0m0rajab1
Ā 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
Ā 
How-Cloud-Computing-Impacts-Businesses-in-2025-and-Beyond.pdf
Artjoker Software Development Company
Ā 

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") } }