Prevent users from submitting multiple times using Angular

There is an issue where users click the save button multiple times, causing a queue of requests to be submitted and resulting in the creation of duplicate data. How can we prevent this on the front-end so that only one request is submitted even if the button is clicked multiple times? Does anyone have a clean implementation or know the techniques to achieve this?

Thank you.

#html code

 <ng-template #editButtons>
      <div class="flex" *ngIf="isEditing">
        <app-page-section-cards-btn
          [btnData]="pageSectionsOptions.btnData.cancel"
          (btnClickEvent)="cancelEdit()"></app-page-section-cards-btn>
        <app-page-section-cards-btn
          [btnData]="pageSectionsOptions.btnData.save"
          (btnClickEvent)="saveDeal()">
      </app-page-section-cards-btn>
      </div>
    </ng-template>

ts code

saveDeal(){
    const payload = {
      "id": 0,
      "name": this.dealDispositionFormFields.dealName,
      "dealType": "Idle Buyout",
      "annualRentProposed": null,
      "annualRentCurrent": null,
      "firmTermRemaining": null,
      "firmTermAdded": null,
      "maxAvailableTerm": null,
      "status": null,
      "capitalContribution": null,
      "parentCloneId": null,
      "accountId": this.currentAccount.accountId,
      "transactionId": this.transactionData.id,
      "dealTypeValues": JSON.stringify(dealTypeValues)
    }
    this.createDispositionDeal(payload);

  }

    createDispositionDeal(payload:any) {
      this._dealService.createDeal(payload)
      .subscribe(
        res=>{
          this._notificationService.showSuccess('Deal was successfully created.');
          if(res.isSuccess){
            this.refreshDealDetailsPage(res.data);
          }  
        },
        err=>{
          console.log('Error creating deal')
        }
      )
    }

Answer №1

If you're looking for a solution using rxjs, consider implementing exhaustMap. Alternatively, you can temporarily disable the button while the call is being processed and enable it once the response is received.

isLoading = false;

saveDeal() {
 this.isLoading = true;
 ...
}


createDispositionDeal(payload:any) {
  this._dealService.createDeal(payload)
  .subscribe(
    res=>{
      this.isLoading = false; // here
      ...
    },
    err=>{
      this.isLoading = false; // here
      ...
    }
  )
}

Don't forget to include a new input in your component with [disabled]="isLoading"

 <app-page-section-cards-btn
      [disabled]="isLoading"
      [btnData]="pageSectionsOptions.btnData.save"
      (btnClickEvent)="saveDeal()">
  </app-page-section-cards-btn>

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

PHP sending only a single space in an email

My HTML form works perfectly fine, except for one field! The issue arises with a particular text field that I fill out using a button and a short JavaScript function. Could this be causing a conflict with the PHP code? The problematic text field is: inpu ...

What methods can be used to verify that window.print() has not been overridden?

Is there a way to verify if the window.print() method is overridden using JavaScript and/or FirefoxDriver? You can prevent all print buttons on a page from functioning like this: window.print = function() { alert("Bazinga") } When this is implemented, a ...

Seeking the perfect message to display upon clicking an object with Protractor

Currently, I am using Protractor 5.1.1 along with Chromedriver 2.27. My goal is to make the script wait until the message "Scheduling complete" appears after clicking on the schedule button. Despite trying various codes (including the commented out code), ...

Please hold off on confirming your RSVP until further interactions have taken place

I have a feature where a component triggers an action when swiped, sending it upwards to the parent route/controller for handling some ajax functionality. The component includes UI elements that indicate a loading state while the action is being processed. ...

Nightwatch failing to locate element within iFrame

I'm currently facing a challenge when trying to access an element within an iframe. Despite successfully switching to the frame, Nightwatch keeps returning "element not found" whenever I attempt to verify its presence or visibility. Below is a snippe ...

What is the process for excluding code lines from coverage analysis in vitest?

I currently have my unit tests configured with vitest and am exploring options to exclude certain lines of code from vitest coverage analysis. Is there a feature in vitest that functions similarly to /* istanbul ignore next */? I've searched through ...

Generate an automatic "proxy" for ASP.NET MVC Controller to communicate with AngularJs service

Whenever I utilize an ASP.NET MVC controller with AngularJS, the majority of my controller functions consist of JSON results. When creating my AngularJS service, I find myself repeatedly writing similar code to handle GET or POST calls to my ASP.NET contro ...

Learn how to retrieve data prior to rendering with Vue 3 and the composition api

Is there a way to fetch data from an API and populate my store (such as user info) before the entire page and components load? I have been struggling to find a solution. I recently came across the beforeRouteEnter method that can be used with the options ...

How can you show the default calendar for a specific month and year in a Vue3 datepicker?

I've been utilizing the @vuepic/vue3datepicker component, which automatically shows the days of the current month when integrated in my project: <template> <VueDatePicker v-model="date" inline></VueDatePicker> </templ ...

Ways to hide the cell tooltip in agGrid?

Is there a way to make the tooltip invisible when hovering over a cell in agGrid? Can a specific value be set on the agGrid options to achieve this? ...

Launching the mongo-dev-server for the project's local mongo database while utilizing an external MongoDB during Meteor Run

Q. How can I leverage mongo-dev-server to utilize an internal MongoDB in my Meteor project while also using an external MongoDB with 'export MONGO_URL'? Explanation: I know that MongoDB should be fully installed for production mode, but sometime ...

Steps to create an automatic submission feature using a combobox in HTML5 and then sending the retrieved data back to the HTML file

Here is the code snippet I've been working on: <strong>Station Name</strong> <!--This portion includes a combobox using HTML5 --> <input type=text list=Stations> <datalist id=Stations> <option>Station1</opt ...

Permission error encountered during Typescript installation

I encountered an error with permissions and paths while attempting to install Typescript. Is there anyone who can help me with successfully installing Typescript? View the Typescript installation error here. ...

Updating the scope in AngularJS/jQuery

I'm currently working on integrating AngularJS into a legacy system that heavily relies on jQuery. I'm facing some challenges when trying to update the scope after retrieving data from an Ajax call. Essentially, the system includes a dropdown th ...

Complete the form even if the field is mandatory by leveraging the Bootstrap Checkout demonstration

I devised a straightforward form for entering text. The input of this text is mandatory. However, when I click on the submit button, the form gets submitted even if the required text field is empty. I took inspiration from this particular Bootstrap templ ...

The BehaviorSubject in Angular's service is causing data duplication issues when used with the Async

Initially, I have a service named ContractorsService, which includes a function called getContractors. This function makes a Firebase Firestore call to the contractors database using the AngularFire method. To manipulate the results from the snapshot, I u ...

The loading of styles in Angular 2 Material is experiencing difficulties

Currently, I am in the process of creating a web application in Angular and I have decided to use the Angular Material library for the user interface. However, I encountered an issue when attempting to import a prebuilt theme. To do so, I included <li ...

Angularjs scope throws TypeError when attempting to add an array

As someone diving into the world of Angular and JavaScript, I am tackling the challenge of creating a directive that requires adding an array to the directive's scope. Here's a snippet of the code for my directive: .directive("startupSections", ...

Reposition the initial element to the end of an array using setInterval() within a React component

I'm attempting to rearrange the elements in an array in React, specifically by moving the first item to the last position using a setInterval function: const [cardOrder, setCardOrder] = useState([card1, card2, card3, card4]); setInterval(() => { ...

The state remains unchanged when useState is invoked

I am currently designing a unique restaurant website template. As part of the project, I have implemented a modal box with two arrow buttons to navigate between pages. The issue I am facing is that the value of the pageNumber variable, tracked using useSta ...