hansontechsolutions.com

Understanding EventEmitter and Subject Differences in Angular

Written on

Chapter 1: Overview of Event Emission in Angular

In Angular, one of the primary functionalities is the ability to pass events between components. For emitting events from a child component to its parent, Angular employs the EventEmitter class. However, many developers often confuse it with the RxJS Subject class, using them interchangeably. Are they really the same?

A look at the source code of EventEmitter reveals that it extends the Subject class. This raises a question: why does Angular choose to extend Subject instead of allowing developers to use it directly?

Section 1.1: Synchronous Nature of EventEmitter and Subject

While EventEmitter and Subject are both synchronous by default, they differ slightly in their implementation. All subscribe functions are executed immediately upon calling emit or next, followed by the next line of code post-execution. For instance, consider the following example:

setValue(5);

The output will be:

RECEIVED: 10

SET: 10

This indicates that the subscribe function runs before the log statement in the setValue function. EventEmitter operates similarly in this regard.

However, it’s important to note that the default behavior of EventEmitter can be modified to function asynchronously. Angular achieves this by wrapping the next, error, and complete functions within a setTimeout, facilitating async behavior.

This video titled "Angular 2 - Output and Custom Events with EventEmitter" illustrates how to utilize EventEmitter effectively for output and custom events in Angular.

Section 1.2: When to Use Async EventEmitter

To better understand the use of async EventEmitter, let’s consider a scenario involving a child component that allows users to select a vehicle from three options. We’ll implement EventEmitter for output in this example, although Subject would behave similarly as a default EventEmitter.

The HTML structure includes three radio buttons, with "Toyota" set as the default selection. The function onVehicleClick is triggered upon changing the selection, which then emits the event to the parent.

The child component performs three actions upon vehicle selection:

  1. Logs the message: "CHILD: Selected New Vehicle {NEW_VEH}".
  2. Emits the event to the parent.
  3. Logs: "REPLACING {OLD_VEH} with {NEW_VEH}" while retrieving the old vehicle value from a service.

The service keeps track of the currently selected vehicle, with "Toyota" as the default.

The parent component listens for the child's event, executing two main tasks:

  1. Logs: "Parent: Setting new vehicle ${NEW_VEH}".
  2. Updates the new vehicle in the service.

We can summarize the overall process as follows:

This tutorial, titled "@Output and EventEmitter in Angular | Angular Tutorial," provides an insightful explanation about how to use @Output and EventEmitter effectively in Angular applications.

Section 1.3: Problem Identification

When the vehicle is changed from "Toyota" to "Honda", the console logs appear as follows:

CHILD: Selected New Vehicle honda

PARENT: Setting new vehicle honda

CHILD: Replacing honda with honda

This is incorrect, as the expected log should have been "Replacing toyota with honda". The underlying issue is that the child component's log executes before the parent function completes.

Section 1.4: Solution to the Problem

The solution lies in making the EventEmitter asynchronous. This can be achieved by passing true when creating the EventEmitter instance, which is not an option available with RxJS Subject.

@Output() vehicleChange$ = new EventEmitter(true); // pass true

Now, when we change the vehicle, the logs will correctly reflect the order:

CHILD: Selected New Vehicle honda

CHILD: Replacing toyota with honda

PARENT: Setting new vehicle honda

This indicates that the child logs execute prior to the parent, ensuring that the parent method runs only after the child method completes.

In conclusion, you now have a clearer understanding of the distinctions between Subject and EventEmitter, along with a specific use case illustrating the advantages of async EventEmitter over Subject.

Share the page:

Twitter Facebook Reddit LinkIn

-----------------------

Recent Post:

The Enigmatic Blue Sky: A Scientific Perspective

Discover the science behind the blue sky, its changes throughout the day, and how pollution impacts its color.

Exploring the Mysteries of Ancient Egyptian Hieroglyphs

Dive into the intriguing theories surrounding ancient Egyptian hieroglyphs, including the controversial

Essential Strategies for Tech Entrepreneurs' Success

Discover vital strategies that can enhance success for tech entrepreneurs based on valuable lessons from digital transformation.