How to deal with double submit in Angular2

前端 未结 6 969
囚心锁ツ
囚心锁ツ 2021-02-02 11:30

If I click fast on my submit-button the form is submitted two or more times. My thought was to prevent this with the disabled attribute, but I need variable disableButon

6条回答
  •  后悔当初
    2021-02-02 12:18

    I have a slight different way (maybe more simple) of dealing with this - same principles apply though.

    Essentially what I will do is:

    • Create a variable called disableButton on the component with an initial value of false
    • Then when the button is clicked set this variable to true
    • Then reset to false once the form is submitted.

    Here is my html template code:

    And here is my class:

    export class UpdateForm {
       disableButton: boolean;
       constructor() { this.disableButton = false; }
       handleSubmit(formData: any, isValid: boolean) {
          if (isValid) {
             this.disableButton = true; // the button will then be disabled
             onHandleUpdate(formData);
          }
       }
       onHandleUpdate(formData) {
          this.disableButton = false; // the button will renable
       }
    }
    

提交回复
热议问题