How to deal with double submit in Angular2

前端 未结 6 968
囚心锁ツ
囚心锁ツ 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:20

    Dealing with double-submission is easy to do wrong. On a form with

    :

    Pass it to your component's submit():

    Accept and use it component-side:

    submit(submitBtn: HTMLButtonElement): void {
        submitBtn.disabled = true;
        /// API calls
        submitBtn.disabled = false;
    }
    

    And if your API calls have multiple pathways that share a common error-handler, you'd need to pass the HTMLButtonElement on through to them as well, since they can no longer pluck it out of the component with this.disableButton.

    (Alternately, instead of declaring and passing #submitBtn, you already have #theForm declared, so pass that instead as :NgForm, and component code can drill-down to the button... or to an overlay over the whole form, or whatever.)

    Whether this solution is more or less elegant than declaring another boolean that works slightly differently than ngForm.submitted is opinion, but it is fact that Angular can't know when the component's submit() and all its async processes are finished without a subscription.

提交回复
热议问题