The other answer does a very poor job of solving the problem. EventEmitters are only meant to be used in conjunction with @Outputs
as well as this problem not taking advantage of the dependency injection built into Angular 2 or the features of RxJS.
Specifically, by not using DI, you're forcing yourself into a scenario where if you reuse the components dependent on the static class they will all receive the same events, which you probably don't want.
Please take a look at the example below, by taking advantage of DI, it is easy to provide the same class multiple times, enabling more flexible use, as well as avoiding the need for funny naming schemes. If you want multiple events, you could 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();
}
}
.emit()
in Bar, and.subscribe()
in Foo Component. Either as@Output()
or via service, like in this example – Palmary@Output()
that much... I prefer the service, I import it in both classes, ask for same instance of emitter and register emit/subscribe where I need, I'll try to create example in a min... – Palmary