Is there no equivalent to $scope.emit()
or $scope.broadcast()
in Angular?
I know the EventEmitter
functionality, but as far as I understand that will just emit an event to the parent HTML element.
What if I need to communicate between fx. siblings or between a component in the root of the DOM and an element nested several levels deep?
We implemented a ngModelChange observable directive that sends all model changes through an event emitter that you instantiate in your own component. You simply have to bind your event emitter to the directive.
See: https://github.com/atomicbits/angular2-modelchangeobservable
In html, bind your event emitter (countryChanged in this example):
In your typescript component, do some async operations on the EventEmitter:
The following code as an example of a replacement for $scope.emit() or $scope.broadcast() in Angular 2 using a shared service to handle events.
Example usage:
Broadcast:
Listener:
It can support multiple arguments:
This is my version:
use:
}
emit:
I'm using a message service that wraps an rxjs
Subject
(TypeScript)Plunker example: Message Service
Components can subscribe and broadcast events (sender):
(receiver)
The
subscribe
method ofMessageService
returns an rxjsSubscription
object, which can be unsubscribed from like so:Also see this answer: https://stackoverflow.com/a/36782616/1861779
Plunker example: Message Service
You can use
EventEmitter orobservables to create an eventbus service that you register with DI. Every component that wants to participate just requests the service as constructor parameter and emits and/or subscribes to events.See also
Service Events: Components can subscribe to service events. For example, two sibling components can subscribe to the same service event and respond by modifying their respective models. More on this below.
But make sure to unsubscribe to that on destroy of the parent component.