Angular EventEmitter coupled with Callbacks

In order to create a custom button component for my angular application and implement a method for click functionality, I have the following code snippet:

export class MyButtonComponent {
  @Input() active: boolean = false;
  @Output() btnClick: EventEmitter<MouseEvent> = new EventEmitter<MouseEvent>();

  @HostListener('click', ['$event'])
  public async onClick(event: MouseEvent) {
      this.active = true;
      await this.btnClick.emit(event);
      this.active = false;
  }
}

The issue I am facing is that when the user clicks the button, the 'active' status becomes true and the event is executed. However, the 'active' status turns false without waiting for the event to finish execution. I would like the 'active' status to be set to false only after the event has fully executed.

How can I address this issue or how can I incorporate a Callback function with the emit method?

Answer №1

If you want to receive notifications from EventEmitters:

this.buttonClick.subscribe(() => this.inactive = true);

This method will provide you with:

export class CustomButtonComponent implements OnInit {
  @Input() inactive: boolean = true;
  @Output() buttonClick: EventEmitter<MouseEvent> = new EventEmitter<MouseEvent>();

  @HostListener('click', ['$event'])
  public onClick(event: MouseEvent) {
      this.inactive = false;
      this.buttonClick.emit(event);
  }
  
  ngOnInit() {
    this.buttonClick.subscribe(() => this.inactive = true);
  }
}

Answer №2

If the Active state is being used as an input, it may make more sense to update its value from the parent component. Consider moving this.active = false; from the MyButtonComponent to the HostComponent within the function that manages the Output.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Understanding the variations in behavior of the history.go(-1) method across various browsers

Is history.go(-1); consistent across all browsers? I've noticed different behaviors on various browsers. In my code, I have a line similar to javascript:history.go(-1); On the first page, there are three checkboxes. Users can only select two of them ...

Try utilizing the Array.map method with a two-dimensional array

My current challenge involves a 2-dimensional Array where I am attempting to implement a "randomBool" function on each of the elements within it. The "randomBool" function essentially generates a random boolean value: const randomBool = () => Boolean( ...

When iteratively utilizing the setValue() function, an unintentional occurrence of an 'Uncaught error' is encountered

I encountered an issue while trying to update a spreadsheet upon submitting a form. The problem is that after pressing the submit button, the remaining commands are not being executed properly. As a result, I see an error message in the console saying "U ...

What is the most effective way to display a star rating determined by the average score?

Currently, I am working on a project using Django and Jquery. The task at hand is to display hotel ratings with stars colored in orange based on an average score obtained from user votes. Let me provide you with an example: score = 8 vote= 2 average = 4 T ...

The attribute specified is not present on the element within the array

I'm attempting to create an array that includes an object with initialized properties and a number. Yet, I encounter this error message: The error states: 'Property 'foo' does not exist on type 'number | IObj'. The proper ...

React with Typescript: Potential occurrence of an undefined object

While working with React and TypeScript, I encountered the error Object is possibly 'undefined' when using language.toLowerCase().includes(selectedCategory). To address this issue, I implemented a check as shown below. Although this resolved th ...

Tips for avoiding special characters when utilizing Jquery serialization?

I'm facing an issue with my form page where I need to perform some AJAX actions before submitting. The problem arises from the fact that the form input names contain period characters, which are causing conflicts in the AJAX functionality. Unfortunate ...

An Axios error message indicates ERR_NETWORK and ERR_EMPTY_RESPONSE

When I initiate a Patch Request from the frontend, it takes approximately 30-40 seconds for the backend to resolve. const handleSendClick = (data: any) => { const requiredLanguages = Array.isArray(data.required_languages) ? data.required_langu ...

Obtaining the blog slug dynamically upon clicking with ReactJS

Currently, I am developing a project using Reactjs and Nextjs. One of the tasks at hand is to obtain the "slug" value after clicking on a blog post. However, at this moment, the value returned is undefined despite trying the following code: <h4 onClic ...

Measuring the quantity of 'table' elements with jQuery

This HTML code below defines a table structure. Now tables can be dynamically added to this structure. <div class="tableStyle myWebsiteTable"> <table cellspacing="0" cellpadding="0" id="site0" class="site active"> <thead> ...

What could be causing this test to fail when testing my API endpoint?

Why am I encountering this error? Uncaught exception: Error: listen EADDRINUSE: address already in use :::3000 import supertest from "supertest" import axios from "axios" import app from ".." const request = supertest(app ...

Seeking assistance with managing Yarn workspaces

My current project involves working on a React Native application for a client. After I had already written a significant amount of code, my client requested a new feature to be added. This feature should have been simple to implement, but due to the compl ...

The field 'shouldComponentUpdate' cannot be reassigned to itself

I encountered a TypeScript error while using shouldComponentUpdate: The error message states: "Property 'shouldComponentUpdate' in type 'Hello' is not assignable to the same property in base type Component<IProps, any, any>." ...

Working with AngularJS: Accessing a JSON file from the local directory

The answers to my previous questions on this topic have not been satisfactory. It seems that most examples and tutorials for AngularJS online always define tiny JSON arrays directly inside the JavaScript code... So, let's simplify things with a basi ...

Best practices for incorporating CSS and JS files into an Angular deployment

I am currently in the process of integrating an Admin Template that I previously used in a traditional PHP application into a new Angular project. <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <link rel= ...

Performing a series of HTTP requests within a single @ngrx/effect

I need some guidance as I am new to @ngrx and feeling a bit lost in understanding how it should be used. Let's assume we have an effect named PlaceOrderEffect In this effect, my goal is to handle each request in a specific order. processOrder$ = cre ...

How to use sinon to create a mock for an independently imported function

Is there a way to successfully mock the axios import using sinon and then set expectations? Here is my attempted code: import axios from 'axios'; axiosMock = sinon.mock(axios); However, the expectation does not pass: describe('Custom test ...

Conceal the scroll bar while still allowing for scrolling functionality

In this code snippet, I am trying to maintain the scroll position of two blocks by syncing them together. Specifically, I want to hide the scrollbar of the left block while scrolling the right one. If anyone has any suggestions or solutions for achieving ...

Suggestions for resolving the error message "Error trying to diff '[object Object]'. Only arrays and iterables are allowed in Angular 10 when working with a specified array[]"

I have been working with Angular 10 for my project. I have a get method in my application to retrieve the data that I want to display. Despite trying various solutions, I am still facing issues with rendering the response data properly. Within my model fi ...

Triggering a sweet alert on a mouse click

Here is a code snippet I found on . It shows an alert box that doesn't disappear when clicked outside of it. swal({ title: "Are you sure?", text: "You will not be able to recover this imaginary file!", type: "warning", showCancelButton: true, ...