Angular 2 shared events

There are certain cases while developing a web app when we have to emit certain events when something occurs or something changes in one component. We want other application component(s) to be notified of the change.

In Angular 2 we have two ways to notify components of those changes.

Output properties

One way is to use Output properties. The way this works is that one component which has the changes to notify, creates an a property with @Output decorator and uses an EventEmitter to emit the event when the change occurs.

Following is an example of such component. Everytime this component is accessed, it will emit an event.

But how will the other component know of this event? That is a valid question. We obviously have to get the other component to subscribe to the events emitted by this one. So, for this to work out, we need this component to be a direct child to another component. That is so because of the unfortunate fact that Output properties don’t bubble. This event will only be emitted up to the first parent. And you can see how it is done below.

Every time you access app component, you will see dashboard component emit an event. You can use a Service or a Directive to emit those events as well.

Shared Service

We can the concept of a shared service to get around the problem of not being able to bubble output properties in Angular 2.

The idea is to create an Angular @Injectible and use it across the application where needed. This service will emit all the necessary events and the components which need can opt in to those events. Here is the sample service code.

We will have to inject this class in app bootstrap to get a single consistent object throughout the app.

And use it in out component like so

alexey

alexey

Application developer, movie buff, occasional reader and a huge Manchester United fan.
alexey

Application developer, movie buff, occasional reader and a huge Manchester United fan.