Fully documented lesson at
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.
1 view
15
2
1 day ago 00:06:30 1
Leadstal vs. Leads Sniper: Which Email Extractor REALLY Gets the Job Done? 😎
1 day ago 00:14:44 1
PhantomBuster vs. Leads Sniper: Which Google Maps Scraper is the Best Choice? 👌
2 weeks ago 00:21:31 1
Killer Instinct (SUPER NES) - Bankaibro vs DonChuto
1 month ago 00:11:44 1
Apple CEO’s High Stake Visit To China For Apology & Request To Market Share
1 month ago 01:52:51 1
Как ФРАНЦИЯ ВЛЮБИЛА мир в АВТОМОБИЛИ. Часть 1.
1 month ago 00:39:26 1
Bob Laramee - Visualizing the Signal From the Noise: Keynote Talk for the ICINC 2024 Conference
1 month ago 00:03:40 1
Полёт на воздушном шаре в парке Солохаул
1 month ago 00:05:16 1
Hair Transplant in Kottayam | Best Results & Cost of Hair Transplant in Kottayam
1 month ago 00:00:52 1
Полёт на воздушном шаре в парке Солохаул. Дата полёта
1 month ago 00:06:15 7
Sauerbraten: Geometry Jailbreak (mesh mover)
1 month ago 00:08:23 1
Как установить Windows 11 с флешки? (Официальная версия)
1 month ago 01:13:43 1
Mentor in Tech 6.0: Кому вы нужны, когда есть OpenAI?
1 month ago 01:05:43 1
MiT 6.0: Как построить стратегию, личную и бизнеса, и найти возможности реализации своего потенциала
1 month ago 00:32:33 1
Nositelé Světla💫: HLASOVKY OD JANIČKY,
1 month ago 00:30:32 1
OceanGate Wreck Shows Why Sub Wasn’t Strong Enough To Survive - NTSB Shares Important Details
1 month ago 00:10:20 1
UK’s MASSIVE Role In Aiding Israel Just Got BLOWN WIDE OPEN!
1 month ago 01:50:08 1
GODDESS OF VICTORY: NIKKE | 2nd Anniversary Livestream
1 month ago 00:40:11 1
Белуха. Одиночный поход по местам силы Алтая
1 month ago 00:09:13 1
Mflex Sounds - Tears in my eyes (Epic ballad version)
1 month ago 00:30:04 1
Spectacular WW2 shell impacts at Gouda! Explore with me, ride along from Gouda to The Hague! 8/10/24
1 month ago 00:30:00 1
Какие Новости принес Вам 🧚♂️Ангел Хранитель🧚♂️
1 month ago 00:12:52 1
💯 May áo rất dễ ngay cả với những người mới bắt đầu |cắt may áo mùa hè đẹp
1 month ago 00:03:49 1
Hair Transplant in Turkey | Best Results & Cost of Hair Transplant in Turkey