Another answer does a very poor job of solving the problem. EventEmitters are for use only in conjunction with @Outputs , as well as this problem not using dependency injection built into Angular 2 or RxJS functions.
In particular, without using DI, you force yourself into a scenario where, if you reuse components that depend on a static class, they will all receive the same events that you probably do not need.
Please take a look at the example below, using DI, it is easy to provide the same class several times, allowing for more flexible use, and also avoiding the need for fun naming schemes. If you need multiple events, you can provide multiple versions of this simple class using opaque tokens.
Working example: http://plnkr.co/edit/RBfa1GKeUdHtmzjFRBLm?p=preview
// The service import 'rxjs/Rx'; import {Subject,Subscription} from 'rxjs/Rx'; export class EmitterService { private events = new Subject(); subscribe (next,error,complete): Subscriber { return this.events.subscribe(next,error,complete); } next (event) { this.events.next(event); } } @Component({ selector: 'bar', template: ` <button (click)="clickity()">click me</button> ` }) export class Bar { constructor(private emitter: EmitterService) {} clickity() { this.emitter.next('Broadcast this to the parent please!'); } } @Component({ selector: 'foo', template: ` <div [ngStyle]="styl"> <ng-content></ng-content> </div> `, providers: [EmitterService], directives: [Bar] }) export class Foo { styl = {}; private subscription; constructor(private emitter: EmitterService) { this.subscription = this.emitter.subscribe(msg => { this.styl = (this.styl.background == 'green') ? {'background': 'orange'} : {'background': 'green'}; }); } // Makes sure we don't have a memory leak by destroying the // Subscription when our component is destroyed ngOnDestroy() { this.subscription.unsubscribe(); } }
source share