Angular, Software Development

Angular Multiple Components With One EventEmitter

This post how to send messages from multiple Angular components using the same EventEmitter. We have three parts – AppComponents, AnotherComponent, and YetAnotherComponent. The setup is usually hierarchical, where we embed the selectors of AnotherComponent and YetAnotherComponent in AppComponent’s HTML. We also have a service that holds an instance of EventEmitter.

For those new to Angular, there is a simpler version of the codes that only involve parent-child components.

Multiple Angular Components

We have three Angular components that have a reference to the TestServiceService service, a very hard-working service! 🙂

Before going to the Angular service codes, let’s review the components’ codes first. For the AppComponent, we set the default message and a way for it to set the message to its original value.

Then, we have the Angular component AnotherComponent, which has an onClick function to send a different message to AppComponent using the shared service that has the EventEmitter.

YetAnotherComponent

Lastly, we have the YetAnotherComponent that sends a different message to AppComponent.

The service looks relatively simple. It only holds a reference to an instance of EventEmitter. Then, the Angular components share this single instance of EventEmitter to communicate with each other.

Our  app.module.ts

Testing Multiple Components With One EventEmitter

When we start the Angular application, we can test it by randomly clicking the buttons. The Angular components, service, and the instance of EventEmitter work their magic! We can notice that the message changes when we click a different button.

Angular Multiple Components EventEmitter

By the way, we are using Angular 8.

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like