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);
    });
}
๐ŸŒ
StackBlitz
stackblitz.com โ€บ edit โ€บ sharing-data-between-angular-components-parent-to-child
Sharing Data Between Angular Components Parent To Child - StackBlitz
Sharing Data from Parent to Child: It works by using the @Input() decorator to allow data to be passed via the template.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ angularjs โ€บ pass-data-between-siblings-in-angular
Pass Data Between Siblings in Angular - GeeksforGeeks
May 14, 2024 - This approach is useful when the sibling components need to share data without relying on parent-child relationships or event emitters. Additionally, it promotes code reusability since the same shared service can be used across different parts of the application where data sharing is required. import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class SharedService { sharedData: any; constructor() { } setData(data: any) { this.sharedData = data; } getData(): any { return this.sharedData; } }
๐ŸŒ
Medium
medium.com โ€บ weekly-webtips โ€บ how-to-pass-data-between-components-in-angular-8-c6bfc0358cd2
How to Pass Data Between Components in Angular 8 | by mike dietz | Webtips | Medium
June 10, 2020 - @Output(), EventEmitter() and Input Stackblitz: Sibling Output-Input Passing data between siblings uses a combination of the aforementioned decorators.
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

๐ŸŒ
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
//assuming that senUnitService is a global service. this.sendUnitService.unitLevel = unitLevel; this.sendUnitService.tribeLevel= tribeLevel; this.sendUnitService.squadLevel= squadLevel; //and if then in the sibling component this.unitLevel = this.sendUnitService.unitLevel; this.tribeLevel = this.sendUnitService.tribeLevel; this.squadLevel = this.sendUnitService.squadLevel; ... Hi and welcome to StackOverflow. There're different possible solution but they depends on your needs. If the the third child is "always" the only one interested to the notification, I'g to pass an Input.
Find elsewhere
๐ŸŒ
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); } }
๐ŸŒ
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.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ angularjs โ€บ establish-communication-between-sibling-components-in-angular-11
Establish communication between sibling components in Angular 11 - GeeksforGeeks
February 23, 2021 - The parent component will catch the data as $event variable. It can use it in a method or transmit it by other means. Finally the @Input() decorator uses a variable and any input through the parent will get stored in this variable.
๐ŸŒ
StackBlitz
stackblitz.com โ€บ edit โ€บ angular7-share-data-between-components
Angular7 Share Data Between Components - StackBlitz
An Angular project based on rxjs, core-js, zone.js, @angular/core, @angular/forms, @angular/common, @angular/router, @angular/compiler, @angular/platform-browser and @angular/platform-browser-dynamic
๐ŸŒ
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.
๐ŸŒ
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.