Event Emitters in Angular

Tram Ho

When you start learning Angular, one of the first things you learn is how to communicate between child and parent components.

Data flow is passed into your component through property bindings, and data flow out of your component is through event bindings.

If you want your component to notify its parent about something, you can use the Output decorator with the EventEmitter to create a custom event. We have the following example:

We can use the Output decorator to label our add as an event that a component can fire to send data to its parent.

And the parent component can listen for an event like this:

Angular will register the add event and call the addTodo() with the data when the component activates the next() .

So what is EventEmitter?

If you look at the code below, you should see something interesting:

We can see that the EventEmitter actually a Subject .

The first thing you can see from the code above is that you can pass a boolean value to EventEmitter to determine whether to send events synchronously or asynchronously (Default is synchronous).

You have the power of Rx

Because EventEmitters are Subject , we can use all of the Rx features. For example, we want to fire an event only when we have a value.

Here you have seen its power yet.

But that is not enough. We also may use any Subject that you want. Try using BehaviorSubject :

EventEmitters! == DOM events

Unlike DOM events, Angular custom events are not event bubbling . What does it mean if you define something like this:

You can only listen to the TodoComponent toggle event in its parent component.

The following code will work:

And the following code does not:

And the solution is

  1. Continue to keep moving the event to the tree

In this example, that’s fine, but can get annoying if you have nested components

  1. Using native DOM events

You could create native DOM events as follows:

The custom event is sent by calling the DispatchEven() . We can pass the data to our event using the detail property.

Event bubbling will work here, but the problem with this approach is that we missed the chance to execute it even in a non-DOM environment like native mobile, native desktop, web worker or server side rendering.

  1. Shared Service

We can use the TodoService as a message bus. You can learn more about this approach from the documentation .

Because EventEmitters are observables, we can do some crazy things with them. Let’s say you have a button component and you need to know when the user finishes pressing all x buttons and then getting the latest value from it.

Share the news now

Source : Viblo