Angular 5: Share data between sibling components using EventEmitter

Panduka Liyanathanthri
3 min readApr 10, 2018

When developing Angular apps you’ll more than likely to come across situations where you have to communicate between two sibling components of your app.

There are several techniques you can use to achieve this. In this article we will be looking at The one using Event Emitters.

This technique uses an Event Emitter to emit an event from a child component to it’s parent using @Output(). The parent component listens to the emitter using event binding, once fired it will bind the input from the emitter to the target child component using input binding.

Component Architecture

This is a simple RSVP app to illustrate this process. The app contains 3 components: App, Events and Event-details. When a user clicks on one of the events from the list on the left, details about the event will be displayed on the right.

Code snippets in the article will only contain code related to the topic. Not the full working app.

Event initiating: Events Component

The Events Component template(events.component.html) binds to a click event on items in the list and calls the onClick method of the view model (events.component.ts).

events.component.html

We create a new Event Emitter output property of type Event, named eventClicked and output it using @Output(). The method onClick is executed once a user clicks on an event in the list and will use the created Event Emitter to emit the clicked event.

The parent: App Component

The template(app.component.html) uses event binding to catch the emitted event: eventClicked from the child and fire the childEventClicked method in the view model(app.component.ts) with event data as parameters.

In the view model, the variable clickedEvent of type Event is initiated and once the childEventClicked method is executed, the variable is set to data received from the original click event of the Events Component. The clickedEvent variable is then bound to the Event Details Component in the App Component’s template above(app.component.html).

Target child: Event Details Component

Event Details Component receives the data passed from the parent component using @Input(). It is assigned to the variable: event.

In the template, *ngIf is used to check whether an event is selected before extracting it’s properties. Otherwise, once the app is started it will crash when it tries to access data which has not been assigned yet.

The template can now render data from the event, selected by the user, using interpolation.

You have now successfully created a mechanism to share data between 2 sibling components in Angular. Do something awesome with what you learned.

--

--