Skip to content

Instantly share code, notes, and snippets.

@christiannwamba
Forked from sasxa/emitter.service.ts
Created July 18, 2016 09:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save christiannwamba/b0142c2dd250d5567f10b44d9976310d to your computer and use it in GitHub Desktop.
Save christiannwamba/b0142c2dd250d5567f10b44d9976310d to your computer and use it in GitHub Desktop.
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) {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment