Angular Component Communication
Angular component communication made easy.
Join the DZone community and get the full member experience.Join For Free
Lately, I was working on a project where we had too many component communication requirements.
The following were the possible solutions to achieve our goals:
- Parent/Child components could communicate using @Input and @Output
- Using the RxJs's Subjects for component communication, not having the parent/ child relationship
We proceeded with creating only `@Output`s and Subjects, but later in the development cycle, we realized that we ended up having too many @Outputs and Subjects created and listened for each type of communication we had.
To simplify this equation a bit, we created a simple yet powerful service to handle the component communication. The idea was, instead of creating multiple Subject or Input/output setups, to create one service that can broadcast messages to all of the listeners, and observers can decide if the broadcasted message is interesting or not.
Here we go, 'event.service.ts':
- If you look closely, it's following the terminology from the Redux world, i.e. action and payload.
- Each broadcasted message will carry the message information.
- Observers listening to the messages can process the messages useful to them.
Broadcasting a Message
Broadcasting a message is as simple as calling a method on the event service with the required information.
As we see here, we are calling the broadcast message as defined in the interface `IMessageProps`. We are defining the message/action type and the payload to process that message.
Listening to the Message
As our event service is nothing but the RxJs's Subject, listening/subscribing to Subject should be simple enough.
As we see here, the Subscriber component is listening to the messages, and if the broadcasted message is of type `DELETE_USER`, that will be processed. The rest all will be ignored (simply because the listener component is not interested in the rest of the messages).
And that's it. We are done. We have component communication that is much simpler, more organized, and easier to understand.
Let me know your thoughts on it.
Connect with me at:
Manish K. Dudeja
Opinions expressed by DZone contributors are their own.