Angular Inter-component Communication Part 2: The Event Emitter

Angular components fit really nicely in a modular, parent/child hierarchy. In part 1 of Angular component communication talks about how parent components call methods living on child components. But how do child components tell the parent component that a specific event has happened? That is the job of the Event Emitter.

Angular components can take in @Input() and @Output(). @Input is how components get data passed in (look out for a post on these, because while very basic you can do some cool thinks with them). @Output is our Event Emitter.

Now that we have the basic child component laid out we can register a handler of the EventEmitter what will be called when .emit() is called. This is called the output handler, and it is defined in the parent component.

This pattern opens up a lot of option for handling events. It is really flexible. The EventEmitter is built on the Observable. The emit() called be view a lot like next(). After looking over this post and the context of ViewChild, the concept of inter-component communication should start to solidify. You can look over the Angular docs for EventEmitter here. The last (but actually probably first) step to inter-component communication is @Input(). While it is pretty intuitive, I will outline it in another post to show off some cool features.

Another note about the EventEmitter is that is takes a boolean in the constructor called isAsync. By defualt this boolean is set to true, meaning EventEmitters are asynchronous. All this means is when the EventEmitter fires, by default, the component zone will run through the rest of it stablization (you dont really need to know what that means. I am just getting into Zones anyway). If set to false (making the EventEmitter synchronous), as soon as the EventEmitter fires, so too will the event handler in the parent component. A post by Ben Nadel talk more about that. But he summarizes that synchronous event handling is rarely needed.

One last bonus, Event Emitters can also be named Outputs. You may run into that in other’s code.

Todd Motto has more words about this stuff if you want even more.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.