Interaction between components — Angular Event Broker Service

Balram Chavan
2 min readSep 14, 2019

Angular application should be built by assembling small and atomic level components which follows SOLID principles. One of the challenge occurs when components needs to pass data and message between each other. If components are in Parent-Child hierarchy then it is very easy to implement using @Input() and @Output() decorators. But when components are not related with each other, then it becomes bit tricky. One of the solution is creating a Dependency Injectable service class which will aggregate events and pass between components. Since it is repetitive process, I have published a npmjs package — ng-event-broker which expose EventBrokerService. In this story we will see how to use it.

Installation

  • Install library in your Angular project using command:

npm install --save ng-event-broker

Usage

  • Import EventBrokerModule from ng-event-broker library
app.module.ts
  • Define your application level events in separate file events.model.ts. For example,
event.model.ts
  • Register application wide events in ngOnInit() of AppComponent. Before publishing or subscribing to any events, they must be registered. As AppComponent is root component, we should define our application wide events here.
app.component.ts
  • Once events are registered, we can publish and subscribe them in rest of application. For example, in below code HeaderComponent subscribe to event cartCountUpdated. Whenever this event is published, onCartUpdated() method will be called. Similarly on Logout button click, HeaderComponent will publish logout event for subscribers to handle it.
header.component.ts

API Reference

Publish event

To publish event, simply call publishEvent(payload) where paylaod can be value of type any. Make sure, event is registered first using `registerEvent()` before publishing.

Subscribe event

To subscribe event, simply call `subscribeEvent()` function which returns `EventEmitter<any>`. You can call `subscribe()` on this event emitter and handle event.

Clear events

We can clear all events using `clearEvents()` function.

Source code and Example

You can find complete source code of very basic eShop demo application and see how events are passed and handled throughout the application.

Demo

You can play around with Demo application here.

--

--

Balram Chavan
Balram Chavan

Written by Balram Chavan

Google Developer Expert Angular | Architect | Author | http://www.youtube.com/@angularcloud

Responses (4)