Skip to content

Instantly share code, notes, and snippets.

@pujansrt
Forked from sasxa/emitter.service.ts
Last active December 28, 2016 07:58
Show Gist options
  • Save pujansrt/b7a609d1eff43f39748901039bc71f38 to your computer and use it in GitHub Desktop.
Save pujansrt/b7a609d1eff43f39748901039bc71f38 to your computer and use it in GitHub Desktop.
Angular2 Communicating between sibling components
import {Component, Input, OnChanges} from "@angular/core";
import {EmitterService} from "../services/emitter.service";
@Component({ selector: 'dispatcher', template: '' })
export class DispatcherComponent implements OnChanges {
@Input() id: string;
value = "dispatcher component value";
ngOnChanges() {
EmitterService.get(this.id).emit(this.value);
}
}
import {Injectable, EventEmitter} from '@angular/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];
}
}
@Component({ selector: 'listener', template: '' })
export 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