Angular : Share data between sibling components

By : Admin  |  Updated On : 26 Feb, 2021

Angular : Share data between sibling components

When a beginner start working on angular they have 1st question how to share data between two different components. There are 3 ways of sharing data between components like below.

  1. Parent to Child
  2. Child to Parent
  3. Sibling to Sibling

Parent to Child OR Child to Parent is easy to share data using @Input and @output decorator in angular. But the question is here how to share data between sibling components. The components which is used parallely side by side. Some people say that 1st send data to parent component and then send the same data to the sibling component. It looks silly and not a good idea.

We can do this in a better way while using angular services and subject rxjs lib. Check the below code step by step.

To do this job need to create a parent component, 2 sibling child component and 1 service. Below are the code example to share data between sibling components.

 

1. In the browser it looks like below image, here we type any thing in the input box of sibling 1 component and the input box text goes to sibling 2 component simultaneously.

share data between sibling component

2. parent.comonent.html ,  here we call the 2 sibling component in parent component

parent component html

3. message.service.ts ,  This is a service file where we create subject object and emit the value from sibling 1 component and get the value from sibling 2 component.

Note : create service with @Injectable({ providedIn: 'root' }) or provide service only in app module so single instance will create of service in entire application.

subject service

4. sibling1.component.ts ,  From here we send(emit) value to the service.

send value to service

5. sibling1.component.html,  Here we create input type text where we type text and the same text send to sibling component 2.

sibling 1 html

6. sibling2.component.ts ,  Here we get the value from the service which is send by sibling 1 component.

sibling 2 component

7. sibling2.component.html ,  Here we print the value which is coming from service which is send by sibling 1 component.

sibling 2 html

That's all to share data between 2 sibling components using service and subject of rxjs library.