As it looks like you are looking to redirect to those components, what you can do is have an event emitter on component one, that on click will emit the data to the parent(of all 3). Then in the parent you would catch the emit, and assign that to data that you pass into the other components.

Component1

import { Component, EventEmitter, Output } from '@angular/core';
import { Router }                          from '@angular/router';

@Component(...)
export class Component1 {
    @Output() redirect:EventEmitter<any> = new EventEmitter();

    data:any = {text: "example"};

    constructor(private router:Router){}

    changeComponent(url:string){
        this.redirect.emit(data);//emits the data to the parent
        this.router.navigate([url]);//redirects url to new component
    }
}

Component2 & Component3

import { Component, Input } from '@angular/core';

@Component(...)
export class Component2 {
    @Input() data:any;
}

Parent

import { Component } from '@angular/core';

@Component(...)
export class Parent {
    parentData:any;
}

Parent.html

<component1 (redirect)="parentData=$event"></component1>
<component2 [data]="parentData"></component2>
<component3 [data]="parentData"></component3>

Another option, if you don't have a parent, is to have a service, that you inject into each parent, and then for the receivers hook into the OnInit lifecycle hook. This works because services are a singleton if in a provider of a shared module.

Service

import { Injectable } from '@angular/core';

@Injectable()
export class SharingService{
    private data:any = undefined;

    setData(data:any){
        this.data = data;
    }

    getData():any{
        return this.data;
    }
}

Component1

import { Component }      from '@angular/core';
import { Router }         from '@angular/router';
import { SharingService } form './sharing.service';

@Component(...)
export class Component1 {

    data:any = {text: "example"};

    constructor(private router:Router,
        private sharingService:SharingService){}

    changeComponent(url:string){
        this.sharingService.setData(this.data);
        this.router.navigate([url]);//redirects url to new component
    }
}

Component2 & Component3

import { Component, OnInit } from '@angular/core';
import { SharingService }    form './sharing.service';

@Component(...)
export class Component2 implements OnInit{
    data:any;

    constructor(private router:Router,
        private sharingService:SharingService){}

    ngOnInit(){
        this.data = this.sharingService.getData();
    }
}

Make sure you add it to providers array of the module.

Module

import { SharingService } from './sharing.service';
...

@NgModule({
    ...
    providers: [ SharingService ]
})
Answer from Joo Beck on Stack Overflow
Top answer
1 of 5
42

As it looks like you are looking to redirect to those components, what you can do is have an event emitter on component one, that on click will emit the data to the parent(of all 3). Then in the parent you would catch the emit, and assign that to data that you pass into the other components.

Component1

import { Component, EventEmitter, Output } from '@angular/core';
import { Router }                          from '@angular/router';

@Component(...)
export class Component1 {
    @Output() redirect:EventEmitter<any> = new EventEmitter();

    data:any = {text: "example"};

    constructor(private router:Router){}

    changeComponent(url:string){
        this.redirect.emit(data);//emits the data to the parent
        this.router.navigate([url]);//redirects url to new component
    }
}

Component2 & Component3

import { Component, Input } from '@angular/core';

@Component(...)
export class Component2 {
    @Input() data:any;
}

Parent

import { Component } from '@angular/core';

@Component(...)
export class Parent {
    parentData:any;
}

Parent.html

<component1 (redirect)="parentData=$event"></component1>
<component2 [data]="parentData"></component2>
<component3 [data]="parentData"></component3>

Another option, if you don't have a parent, is to have a service, that you inject into each parent, and then for the receivers hook into the OnInit lifecycle hook. This works because services are a singleton if in a provider of a shared module.

Service

import { Injectable } from '@angular/core';

@Injectable()
export class SharingService{
    private data:any = undefined;

    setData(data:any){
        this.data = data;
    }

    getData():any{
        return this.data;
    }
}

Component1

import { Component }      from '@angular/core';
import { Router }         from '@angular/router';
import { SharingService } form './sharing.service';

@Component(...)
export class Component1 {

    data:any = {text: "example"};

    constructor(private router:Router,
        private sharingService:SharingService){}

    changeComponent(url:string){
        this.sharingService.setData(this.data);
        this.router.navigate([url]);//redirects url to new component
    }
}

Component2 & Component3

import { Component, OnInit } from '@angular/core';
import { SharingService }    form './sharing.service';

@Component(...)
export class Component2 implements OnInit{
    data:any;

    constructor(private router:Router,
        private sharingService:SharingService){}

    ngOnInit(){
        this.data = this.sharingService.getData();
    }
}

Make sure you add it to providers array of the module.

Module

import { SharingService } from './sharing.service';
...

@NgModule({
    ...
    providers: [ SharingService ]
})
2 of 5
15

Since you have asked to share the data between sibling components we can achieve it by using BehaviourSubject in service.

The BehaviorSubject holds the value that needs to be shared with other components. These components subscribe to data which is simple returning the BehaviorSubject value without the functionality to change the value.

Service.ts

import { Observable, BehaviorSubject } from 'rxjs';

export class Service {
       private data = new BehaviorSubject("")
       currentData = this.data.asObservable();

 constructor() { }

 setData(data) {
      this.data.next(data);
 }

Component1.ts

import { Service } from '../service.service';

export class component1 implements OnInit {

data: any;

constructor (private service: Service) {}

sendDataToService() {
     this.service.setData(this.data);
}

Component2.ts

import { Service } from '../../service.service';

export class component2 implements OnInit {

constructor ( private service: Service ) { }

ngOnInit() {
    this.service.currentData.subscribe(data => {
      console.log(data);
    });
}
🌐
GeeksforGeeks
geeksforgeeks.org › angularjs › pass-data-between-siblings-in-angular
Pass Data Between Siblings in Angular - GeeksforGeeks
May 14, 2024 - This approach involves using Input and Output properties to establish communication between sibling components. The parent component acts as an intermediary and passes data from one sibling component to another using property bindings.
Discussions

Angular 2 Sibling Component Communication
With everything in Angular 2 being a component, I'm surprised there's not more information out there about component communication. Is there another/more straightforward way to accomplish this? ... Did u found any way for sibling data sharing ? I need it as observable.. ... Updated to rc.4: When trying to get data passed between ... More on stackoverflow.com
🌐 stackoverflow.com
angular - How to pass data to an exact sibling component? - Stack Overflow
93 How to Pass data from child to parent component Angular · 6 Passing Data between sibling components in Angular More on stackoverflow.com
🌐 stackoverflow.com
routes - How can I pass data between sibling components in Angular? - Stack Overflow
I’m building an ecommerce app with Angular, I wonder how can I pass the total amount from the ShoppingCart component to the Checkout component. The two components are sibling. I saw few ways to do... More on stackoverflow.com
🌐 stackoverflow.com
Share data between sibling components

I tend to use Subjects via services:

https://angularfirebase.com/lessons/sharing-data-between-angular-components-four-methods/

I'm sure there are other ways of doing this but the above tutorial is very straight forward and covers different types of component relationships.

More on reddit.com
🌐 r/angular
4
3
October 7, 2019
🌐
DEV Community
dev.to › fanmixco › transfer-data-between-siblings-components-in-angular-a1m
Transfer Data between Siblings Components in Angular with RxJS - DEV Community
March 19, 2024 - This library is the one that is going to do the trick to transfer it. I'm going to focus on the Siblings part since the other one (child to parent) is easier and well documented between @Outputs and @Inputs. First, let's create a service for transferring the data between Siblings:
🌐
GeeksforGeeks
geeksforgeeks.org › angularjs › establish-communication-between-sibling-components-in-angular-11
Establish communication between sibling components in Angular 11 - GeeksforGeeks
February 23, 2021 - In Angular, we can achieve this using its inbuilt features: The @Output decorator helps in emitting the data through an EventEmitter<T> object. We will see its working through the example. The parent component will catch the data as $event variable.
🌐
C# Corner
c-sharpcorner.com › article › share-data-between-sibling-components-in-angular-using-rxjs-behaviorsubject
Share Data Between Sibling Components In Angular Using Rxjs BehaviorSubject
May 29, 2018 - Here we will discuss how to share data between sibling components using Rxjs Behavior Subject in Angular 5 project with step by step demonstration.
🌐
Perficient Blogs
blogs.perficient.com › 2024 › 01 › 23 › different methods to share data between components in angular – part 1
Different Methods to Share Data Between Components in Angular - Part 1 / Blogs / Perficient
January 23, 2024 - Methods to share data between components are as follows: Using input properties, you can send data from the parent component to the child component and use output properties to get data from the child component to the parent component.
Find elsewhere
🌐
YouTube
youtube.com › christian hur
How Sibling Components Communicate in Angular Explained - YouTube
⭕ OverviewIn this video, I'll explain the concept of how Angular passes data from a Child component to another Child component (sibling component communicati...
Published   October 2, 2022
🌐
Blogger
thecodepoints.blogspot.com › home › angular › how to pass data between sibling components in angular
How To Pass Data Between Sibling Components In Angular
August 22, 2022 - Now, Add the following code under the dataService.ts for passing data between components. import { Injectable } from '@angular/core'; import { BehaviorSubject, Subject } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class DataServiceService { // SharingData = new Subject(); SharingData = new BehaviorSubject('default'); constructor() { } changeDataSubject(data: any) { this.SharingData.next(data.value); } }
Top answer
1 of 13
68

Updated to rc.4: When trying to get data passed between sibling components in angular 2, The simplest way right now (angular.rc.4) is to take advantage of angular2's hierarchal dependency injection and create a shared service.

Here would be the service:

import {Injectable} from '@angular/core';

@Injectable()
export class SharedService {
    dataArray: string[] = [];

    insertData(data: string){
        this.dataArray.unshift(data);
    }
}

Now, here would be the PARENT component

import {Component} from '@angular/core';
import {SharedService} from './shared.service';
import {ChildComponent} from './child.component';
import {ChildSiblingComponent} from './child-sibling.component';
@Component({
    selector: 'parent-component',
    template: `
        <h1>Parent</h1>
        <div>
            <child-component></child-component>
            <child-sibling-component></child-sibling-component>
        </div>
    `,
    providers: [SharedService],
    directives: [ChildComponent, ChildSiblingComponent]
})
export class parentComponent{

} 

and its two children

child 1

import {Component, OnInit} from '@angular/core';
import {SharedService} from './shared.service'

@Component({
    selector: 'child-component',
    template: `
        <h1>I am a child</h1>
        <div>
            <ul *ngFor="#data in data">
                <li>{{data}}</li>
            </ul>
        </div>
    `
})
export class ChildComponent implements OnInit{
    data: string[] = [];
    constructor(
        private _sharedService: SharedService) { }
    ngOnInit():any {
        this.data = this._sharedService.dataArray;
    }
}

child 2 (It's sibling)

import {Component} from 'angular2/core';
import {SharedService} from './shared.service'

@Component({
    selector: 'child-sibling-component',
    template: `
        <h1>I am a child</h1>
        <input type="text" [(ngModel)]="data"/>
        <button (click)="addData()"></button>
    `
})
export class ChildSiblingComponent{
    data: string = 'Testing data';
    constructor(
        private _sharedService: SharedService){}
    addData(){
        this._sharedService.insertData(this.data);
        this.data = '';
    }
}

NOW: Things to take note of when using this method.

  1. Only include the service provider for the shared service in the PARENT component and NOT the children.
  2. You still have to include constructors and import the service in the children
  3. This answer was originally answered for an early angular 2 beta version. All that has changed though are the import statements, so that is all you need to update if you used the original version by chance.
2 of 13
29

In case of 2 different components (not nested components, parent\child\grandchild ) I suggest you this:

MissionService:

import { Injectable } from '@angular/core';
import { Subject }    from 'rxjs/Subject';

@Injectable()

export class MissionService {
  // Observable string sources
  private missionAnnouncedSource = new Subject<string>();
  private missionConfirmedSource = new Subject<string>();
  // Observable string streams
  missionAnnounced$ = this.missionAnnouncedSource.asObservable();
  missionConfirmed$ = this.missionConfirmedSource.asObservable();
  // Service message commands
  announceMission(mission: string) {
    this.missionAnnouncedSource.next(mission);
  }
  confirmMission(astronaut: string) {
    this.missionConfirmedSource.next(astronaut);
  }

}

AstronautComponent:

import { Component, Input, OnDestroy } from '@angular/core';
import { MissionService } from './mission.service';
import { Subscription }   from 'rxjs/Subscription';
@Component({
  selector: 'my-astronaut',
  template: `
    <p>
      {{astronaut}}: <strong>{{mission}}</strong>
      <button
        (click)="confirm()"
        [disabled]="!announced || confirmed">
        Confirm
      </button>
    </p>
  `
})
export class AstronautComponent implements OnDestroy {
  @Input() astronaut: string;
  mission = '<no mission announced>';
  confirmed = false;
  announced = false;
  subscription: Subscription;
  constructor(private missionService: MissionService) {
    this.subscription = missionService.missionAnnounced$.subscribe(
      mission => {
        this.mission = mission;
        this.announced = true;
        this.confirmed = false;
    });
  }
  confirm() {
    this.confirmed = true;
    this.missionService.confirmMission(this.astronaut);
  }
  ngOnDestroy() {
    // prevent memory leak when component destroyed
    this.subscription.unsubscribe();
  }
}

Source: Parent and children communicate via a service

🌐
LinkedIn
linkedin.com › pulse › data-sharing-between-components-raj-kale
Data Sharing Between Components - Raj Kale
April 7, 2021 - import { Component} from '@angular/core'; @Component({ selector: 'parent-component', template: ` <child1-component [messageToChild1] = "messageToChild2" (messageFromChild1)="getDataFromChild1($event)"> </child1-component> <child2-component [messageToChild2] = "messageToChild1" (messageFromChild2)="getDataFromChild1($event)"> </child2-component> `, styleUrls: ['./parent.component.css'] }) export class ParentComponent { public messageToChild1: string; public messageToChild2: string; constructor() { } // Cross component data passing for sibling componets getDataFromChild1(message: string) { this.
🌐
www.fiveminute.in
fiveminute.in › home › technology › programming
Angular : Share data between sibling components
February 26, 2021 - 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.
🌐
YouTube
youtube.com › ayyaztech
How to pass data to sibling component in Angular 17? - YouTube
🌟 Exclusive Hosting Deal from Hostinger 🌟Ready to launch your own website? Use my affiliate link to get an exclusive discount on Hostinger's reliable and h...
Published   December 22, 2023
Views   3K
🌐
LinkedIn
linkedin.com › pulse › data-sharing-between-components-raj-kale
Data Sharing Between Components
July 4, 2021 - import { Component} from '@angular/core'; @Component({ selector: 'parent-component', template: ` <child1-component [messageToChild1] = "messageToChild2" (messageFromChild1)="getDataFromChild1($event)"> </child1-component> <child2-component [messageToChild2] = "messageToChild1" (messageFromChild2)="getDataFromChild1($event)"> </child2-component> `, styleUrls: ['./parent.component.css'] }) export class ParentComponent { public messageToChild1: string; public messageToChild2: string; constructor() { } // Cross component data passing for sibling componets getDataFromChild1(message: string) { this.
🌐
Stack Overflow
stackoverflow.com › questions › 58967581 › how-to-pass-data-to-an-exact-sibling-component
angular - How to pass data to an exact sibling component? - Stack Overflow
I have three sibling components which are populated using the same component as follows. <div *ngIf="unitLevel && tribeLevel && squadLevel"> <at-unit-search [level]="unitLevel"></at-unit-search> <at-unit-search [level]="tribeLevel"></at-unit-search> <at-unit-search [level]="squadLevel"></at-unit-search> </div> I need to pass some data from first sibling to third sibling, but not to second sibling.I used a service for this.
🌐
codestudy
codestudy.net › blog › angular-2-sibling-component-communication
Angular 2 Sibling Component Communication: How to Pass Data Between List and Detail Components Without Routing (Event Emitters vs Shared Service) — codestudy.net
This method uses Angular’s built-in @Output() decorator and EventEmitter to send data from the ListComponent to the parent, which then passes it to the DetailComponent via @Input(). First, create a new Angular project and generate the required components: ng new sibling-communication-demo cd sibling-communication-demo ng generate component parent ng generate component list ng generate component detail
🌐
Angulartutorial
angulartutorial.net › 2017 › 12 › share-data-between-sibling-components.html
Make It Easy: Share data between sibling components - Angular 2+
December 20, 2017 - We are done for our components, now we need to update our parent component to pass the data. import { Component } from '@angular/core'; @Component({ selector: 'app-root', template: '<div>' + '<home (shareDataEvent) = "dashboard.sendData($event)"></home>' + '<dashboard #dashboard></dashboard>' + '</div>', }) export class AppComponent { constructor() { } } Here HomeComponent is emitting the data to parent and from parent it is sharing to DashboardComponent. There are many other ways also there to share data between components.
🌐
Medium
afifalfiano.medium.com › angular-sharing-data-between-components-with-input-output-5df0c9cf6ec8
Angular: Sharing Data Between Components With @Input @Output | by Afif Alfiano | Medium
February 26, 2023 - So, on the function onSendFeedback we pass the value feedback with emit data on the variable childToParent. ... So, the project will be like this. ... Maybe, In another case, we want to share data between component A and component B on the same page or container component. Look at the image below. ... First, generate component container, sibling one and sibling two.
🌐
Medium
medium.com › @elouadinouhaila566 › sharing-data-between-components-in-angular-37a816a873d4
Sharing Data Between Components In Angular | by Nouhaila El Ouadi | Medium
September 5, 2024 - In Angular, sharing data between ... a parent component needs to pass data to a child component, you can use the @Input decorator in the child component....