Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing Data between sibling components in Angular

Tags:

angular

enter image description here Above image depicts my Angular 2 application , Main component has two child components "FromComponent" and "ToComponent".

"FromComponent" displays a list of items with a checkbox beside each item.

When user selects/deselects an item in FromComponent , it should be added/removed from ToComponent list of items.

what is the best way to implement this in angular 2 ?

like image 794
refactor Avatar asked Jun 06 '17 16:06

refactor


People also ask

Can we send data from one component to another in Angular?

When we build components in an application, we maybe need to share or send data from parent to child or without a direct connection. Angular provides different these ways to communicate components: Using Input() and Output() decorators. Using Viewchild decorator.


Video Answer


2 Answers

You would want to use a shared service that stores this information. Using observables as the storage mechanism would allow the To Component to subscribe to that subject and watch for any changes that the From component makes to that observable.

Check out more information on Subject and BehaviorSubject types in rxjs.

like image 136
jLee Avatar answered Nov 07 '22 20:11

jLee


I have implemented that using a service as described here where parent-child communication is described. A service can connect a parent with all its children.

like image 37
Giannis Koumoutsos Avatar answered Nov 07 '22 21:11

Giannis Koumoutsos