Sharing Data between Components in Angular

Share this & earn $10
Fireship
Published at : 29 Dec 2020
337214 views
5055
109

Fully documented lesson at https://angularfirebase.com/lessons/sharing-data-between-angular-components-four-methods/

In this episode, I am going to show you four different ways to share data between Angular components.

Parent to Child the Input Decorator

When you declare a variable with the Input decorator in the child component, it allows that variable to be received from a parent template. In this case, we define a message variable in the parent, then use square brackets to pass the data to the child. Now the child can display this data in its own template.

Child to Parent via ViewChild

ViewChild allows a one component to be injected into another, giving the parent access to its attributes and functions. One caveat, 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.

In the AfterViewInit function we can access the message variable defined in the child

Child to Parent via Output and EventEmitter

Another way to share data is to emit data from the child, which can be listed to by the parent. This approach is ideal when you want to share data changes that occur on things like button clicks, form entires, and other user events.

In the child, we declare a messageEvent variable with the Output decorator and set it equal to a new event emitter. Then we create a function named sendMessage that calls emit on this event with the message we want to send. Lastly, we create a button to trigger this function.

In the parent, we create a function to receive the message and set it equal to the message variable.

The parent can now subscribe to this messageEvent that's outputted by the child component, then run the receive message function whenever this event occurs.

Share data between any components

When passing data between components that lack a direct connection, such as siblings, grandchildren, etc, you should you a shared service. When you have data that should aways been in sync, I find the RxJS `BehaviorSubject` very useful in this situation. The main benefit that a BehaviorSubject ensures that every component consuming the service receives the most recent data.


In the service, we create a private BehaviorSubject that will hold the current value of the message. We define a currentMessage variable handle this data stream as an observable that will be used by the components. Lastly, we create function that calls next on the BehaviorSubject to change its value.

The parent, child, and sibling components all receive the same treatment. We inject the DataService in the constructor, then subscribe to the currentMessage observable and set its value equal to the message variable.

Now if we create a function in any one of these components that changes the value of the message. when this function is executed the new data it's automatically broadcast to all other components.

That's it for data sharing. See you next time.
angularangular 4angular 2

My Favourite Romance Books of 2020 (Best Books of 2020)

My Favourite Romance Books of 2020 (Best Books of 2020)

I Tried To Kiss My Bestfriend😘💕 |#2 TikTok Challenge Compilation

I Tried To Kiss My Bestfriend😘💕 |#2 TikTok Challenge Compilation

5.A Right Attitude To Money - Zac Poonen

5.A Right Attitude To Money - Zac Poonen

Properties of Functions - Increasing vs Decreasing (Precalculus - College Algebra 9)

Properties of Functions - Increasing vs Decreasing (Precalculus - College Algebra 9)

How To Make Spaghetti The Correct Way

How To Make Spaghetti The Correct Way

Giving Reddit Relationship Advice - SimplyPodLogical #35

Giving Reddit Relationship Advice - SimplyPodLogical #35

Online Registration of establishment in EPFO

Online Registration of establishment in EPFO

Motorama — Devoid Of Color (Official Audio)

Motorama — Devoid Of Color (Official Audio)

[hate5six] Turnstile - July 27, 2014

[hate5six] Turnstile - July 27, 2014

WWE 2K19 Giant Rey Mysterio vs Mini WWE Superstars Match!

WWE 2K19 Giant Rey Mysterio vs Mini WWE Superstars Match!

Mechanism of Injury and Spinal Injuries

Mechanism of Injury and Spinal Injuries

Snoop Dogg - Regulate feat.Warren G - Paris Zénith 2011

Snoop Dogg - Regulate feat.Warren G - Paris Zénith 2011

Explanation of Old Balance? | Power Pack | a strong product of PrPal | Estonia | Crypto Earning |

Explanation of Old Balance? | Power Pack | a strong product of PrPal | Estonia | Crypto Earning |

Intelligent Grading Solution - Grade Tests Quickly, Distribute Results Easily

Intelligent Grading Solution - Grade Tests Quickly, Distribute Results Easily

Color song , Learn Colors Ball with Mommy,Öykü and  cute characters

Color song , Learn Colors Ball with Mommy,Öykü and cute characters

Metalcraft Tools, Ornamental Metalwork, Wrought Iron, metalcraft uk

Metalcraft Tools, Ornamental Metalwork, Wrought Iron, metalcraft uk

Just chilliness

Just chilliness

The GREATEST Among Us Animations On YouTube..

The GREATEST Among Us Animations On YouTube..

Canopy HQ Demo | Overview of Canopy Tenant Referencing Process

Canopy HQ Demo | Overview of Canopy Tenant Referencing Process

Suffering from Fungal Infection, Ringworms? WATCH THIS!

Suffering from Fungal Infection, Ringworms? WATCH THIS!

Why it's Essential to Flush Kidneys Toxins after Every 15 Days?  - Kidney Detox Home Remedy

Why it's Essential to Flush Kidneys Toxins after Every 15 Days? - Kidney Detox Home Remedy

USED TO / USE TO / BE USED TO / GET USED TO / WOULD DO - English Grammar Lesson with Examples & Quiz

USED TO / USE TO / BE USED TO / GET USED TO / WOULD DO - English Grammar Lesson with Examples & Quiz

DO NOT EMBARRASS YOURSELF! 40 Unspoken Etiquette Rules

DO NOT EMBARRASS YOURSELF! 40 Unspoken Etiquette Rules

Alexis Ohanian: How to make a splash in social media

Alexis Ohanian: How to make a splash in social media

The La's - Feelin'

The La's - Feelin'

🔵 Wary Vs Weary - Vocabulary Builder 2 - ESL British English Pronunciation

🔵 Wary Vs Weary - Vocabulary Builder 2 - ESL British English Pronunciation

Modern Talking-You’re My Heart, You’re My Soul (cover Ladynsax)

Modern Talking-You’re My Heart, You’re My Soul (cover Ladynsax)

EDIBLE - (OFFICIAL AUDIO) | Nicole TV

EDIBLE - (OFFICIAL AUDIO) | Nicole TV

Aircraft Marshalling and Push back Procedure

Aircraft Marshalling and Push back Procedure

मटन वाला कहानी - Greedy Mutton Seller Story |  Hindi Kahaniya | Stories in Hindi | Kahaniya

मटन वाला कहानी - Greedy Mutton Seller Story | Hindi Kahaniya | Stories in Hindi | Kahaniya

One hundred and seventy thousand cancer cases every year in Pakistan

One hundred and seventy thousand cancer cases every year in Pakistan

Autumn Leaves - Soloing with Arpeggios  - Jazz Guitar lesson

Autumn Leaves - Soloing with Arpeggios - Jazz Guitar lesson

I've Been Texting The WRONG PERSON For 10 Years (Animated Story Time)

I've Been Texting The WRONG PERSON For 10 Years (Animated Story Time)

Shoulder Dislocation reduced in less than 5 second (Hippocratic Method)

Shoulder Dislocation reduced in less than 5 second (Hippocratic Method)

Ray Wilson | You Could Have Been Someone

Ray Wilson | You Could Have Been Someone

The limits of enjoyment between the husband and his wife  #HUDATV

The limits of enjoyment between the husband and his wife #HUDATV

Kpop Idols Kiss On Stage

Kpop Idols Kiss On Stage

How to fold jeans for display |Travel

How to fold jeans for display |Travel

5 NEW Ores that could be in Minecraft 1.15!

5 NEW Ores that could be in Minecraft 1.15!

Double MURDER | Cold Justice | Crime Documentary (True Crime) | Reel Truth Crime

Double MURDER | Cold Justice | Crime Documentary (True Crime) | Reel Truth Crime

Elementary Stories for Reproduction 2 Audio CD

Elementary Stories for Reproduction 2 Audio CD

Cats Reacting To The First Snow Funny Compilation

Cats Reacting To The First Snow Funny Compilation

Depreciation of construction equipment

Depreciation of construction equipment

Timeflies - Once in a While Lyrics

Timeflies - Once in a While Lyrics

Unreal Past Conditionals and Wishes PIERCE COLLEGE

Unreal Past Conditionals and Wishes PIERCE COLLEGE

best cosmo moments fairly odd parents!

best cosmo moments fairly odd parents!

UPDF ready to take part in the construction of the Standard Gauge Railway - Maj.General Mugira

UPDF ready to take part in the construction of the Standard Gauge Railway - Maj.General Mugira

Meeting everyone once again | Revisiting 2020 | Happy New year 2021 | Simply sruthi *news channel*

Meeting everyone once again | Revisiting 2020 | Happy New year 2021 | Simply sruthi *news channel*

Accordingly Meaning

Accordingly Meaning