In Angular 2 what is the difference between Event Emitter and Subject for announcing an event? It seems like event emitters are less complicated to declare....Which way is preferred by Angular 2?
dataRefreshEvent = new EventEmitter(); private companyDataAnnouncedSource = new Subject(); companyDataAnnouncedSource$ = this.companyDataAnnouncedSource.asObservable();
Conclusion. Use Eventemitter when transferring data from child component to parent component. Use Subject to transfer data from one component to another component.
EventEmitter is used in the directives and components to emit custom events either synchronously or asynchronously. Since EventEmitter class extends RxJS subject class, this means it is observable and can be multicasted to many observers.
🎊 Event Emitters in Angular 🎊Data flows into your component via property bindings and flows out of your component through event bindings. If you want your component to notify his parent about something you can use the Output decorator with EventEmitter to create a custom event.
There is not much difference. EventEmitter
extends Subject
.
The Angular2 team stressed the fact though, that EventEmitter
should not be used for anything else then @Output()
s in components and directives.
The Angular team has stated that they may change the underlying implementation of EventEmitter
and break user code that uses EventEmitter
for something it wasn't intended for. That's the main difference.
Also EventEmitter
gets cleaned up automatically unlike custom Subjects
that you need to unsubscribe to in the onDestroy
lifecycle hook.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With