Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Angular2 Communicating between sibling components
import {Injectable, EventEmitter} from 'angular2/core';
@Injectable()
export class EmitterService {
private static _emitters: { [ID: string]: EventEmitter<any> } = {};
static get(ID: string): EventEmitter<any> {
if (!this._emitters[ID])
this._emitters[ID] = new EventEmitter();
return this._emitters[ID];
}
}
import {Component, Input, OnChanges} from 'angular2/core';
import {EmitterService} from './emitter.service';
@Component({ selector: 'dispatcher', template: '' })
class DispatcherComponent implements OnChanges {
@Input() id: string;
private value = "dispatcher component value";
doStuff() {
EmitterService.get(this.id).emit(value);
}
}
@Component({ selector: 'listener', template: '' })
class ListenerComponent implements OnChanges {
@Input() id: string;
ngOnChanges() {
EmitterService.get(this.id).subscribe(value => console.log(value));
}
}
@Component({
providers: [EmitterService],
selector: 'host',
template: `
<dispatcher [id]="host_id"></dispatcher>
<listener [id]="host_id"></listener>
`
})
export class HostComponent {
public host_id: "HOST_COMPONENT";
constructor(private _emitterService: EmitterService) {}
}
@mcabreradev

This comment has been minimized.

Copy link

commented Jul 7, 2016

Geat!! thanks a lot.. this gist help me!

@akankshagaur

This comment has been minimized.

Copy link

commented Oct 26, 2016

Thanks a lot, it helped me create a module level messaging service.

@nikitpatel24

This comment has been minimized.

Copy link

commented Oct 31, 2016

I get the following error but when i console.log('this.id'), this prints the value of host_id in both child components.

error_handler.js:48 EXCEPTION: Cannot read property 'emit' of undefinedErrorHandler.handleError @ error_handler.js:48next @ application_ref.js:298schedulerFn @ async.js:89SafeSubscriber.__tryOrUnsub @ Subscriber.js:223SafeSubscriber.next @ Subscriber.js:172Subscriber._next @ Subscriber.js:125Subscriber.next @ Subscriber.js:89Subject.next @ Subject.js:55EventEmitter.emit @ async.js:81NgZone.triggerError @ ng_zone.js:280onHandleError @ ng_zone.js:259ZoneDelegate.handleError @ zone.js:236Zone.runTask @ zone.js:157ZoneTask.invoke @ zone.js:335
error_handler.js:53 ORIGINAL STACKTRACE:ErrorHandler.handleError @ error_handler.js:53next @ application_ref.js:298schedulerFn @ async.js:89SafeSubscriber.__tryOrUnsub @ Subscriber.js:223SafeSubscriber.next @ Subscriber.js:172Subscriber._next @ Subscriber.js:125Subscriber.next @ Subscriber.js:89Subject.next @ Subject.js:55EventEmitter.emit @ async.js:81NgZone.triggerError @ ng_zone.js:280onHandleError @ ng_zone.js:259ZoneDelegate.handleError @ zone.js:236Zone.runTask @ zone.js:157ZoneTask.invoke @ zone.js:335
error_handler.js:54 TypeError: Cannot read property 'emit' of undefined
at SafeSubscriber._next (grid.component.ts:13)
at SafeSubscriber.__tryOrUnsub (Subscriber.js:223)
at SafeSubscriber.next (Subscriber.js:172)
at Subscriber._next (Subscriber.js:125)
at Subscriber.next (Subscriber.js:89)
at MapSubscriber._next (map.js:83)
at MapSubscriber.Subscriber.next (Subscriber.js:89)
at XMLHttpRequest.onLoad (xhr_backend.js:82)
at ZoneDelegate.invokeTask (zone.js:265)
at Object.onInvokeTask (ng_zone.js:229)ErrorHandler.handleError @ error_handler.js:54next @ application_ref.js:298schedulerFn @ async.js:89SafeSubscriber.__tryOrUnsub @ Subscriber.js:223SafeSubscriber.next @ Subscriber.js:172Subscriber._next @ Subscriber.js:125Subscriber.next @ Subscriber.js:89Subject.next @ Subject.js:55EventEmitter.emit @ async.js:81NgZone.triggerError @ ng_zone.js:280onHandleError @ ng_zone.js:259ZoneDelegate.handleError @ zone.js:236Zone.runTask @ zone.js:157ZoneTask.invoke @ zone.js:335
grid.component.ts:13 Uncaught TypeError: Cannot read property 'emit' of undefined(…)

@Lauris01

This comment has been minimized.

Copy link

commented Nov 9, 2016

Thank you for sharing 👍

@engrashid

This comment has been minimized.

Copy link

commented Dec 2, 2016

Helped me to do my task.
thanks

@fabirydel

This comment has been minimized.

Copy link

commented Jan 6, 2017

Really helped me out, thank you.

@godie

This comment has been minimized.

Copy link

commented Mar 5, 2017

thank you for the code

@Safiyya

This comment has been minimized.

Copy link

commented Mar 9, 2017

Thanks for sharing, it helps a lot !

@tapmapp

This comment has been minimized.

Copy link

commented Mar 29, 2017

Hello mate, thanks for sharing! I am trying to call a function of a component from a sibling component. Any idea on how to do it? Thanks in advance!

@assaftenen

This comment has been minimized.

Copy link

commented Mar 30, 2017

Thanks! really helpful.
Q - those the components must be siblings? As I see the can be totally foreign components that only share the service.
Or I just got it wrong?

@RamanaVukoti

This comment has been minimized.

Copy link

commented Jun 27, 2017

nice one .. thanks

@sahinerbay

This comment has been minimized.

Copy link

commented Nov 10, 2017

EventEmitter is not meant to be used inside a service. They should be used only for emitting custom events inside components. You can use RxJS BehaviorSubject instead!

@ramesh-thati

This comment has been minimized.

Copy link

commented Jan 4, 2018

This very nice example, for communication between cross components.

@ramesh-thati

This comment has been minimized.

Copy link

commented Jan 4, 2018

I am facing below issues. Please help me.
Created one parent component and name is product component. inside product component i have two child component and these child components are siblings.
1, product info and
2, product details.
I am looping these siblings product from parent component.
In side product info component i have one button as a show details. When i click on show detail button needs to display in product detail component.
for acheving this i used event emmiter service.
When i subscribing event emitters service in product details component it's looping

@Ravindarreddykarne

This comment has been minimized.

Copy link

commented Mar 21, 2018

I am facing below issues. Please help me.
Created one parent component and name is book-list component.and another one component is created if i click book-list component book title how to come book-details in book-details page

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.