在Angular 9 Web应用程序中禁用Submit上的提交按钮,这样就不会出现多个表单提交的情况。

问题描述 投票:0回答:1

我的Angular 9应用程序在用户多次点击提交按钮时发送多个表单提交时遇到了一个问题,我想在提交按钮验证后禁用提交按钮,提交被触发,直到表单提交并重置,我已经设计了表单使用模态,当表单被接受或拒绝时,但很多时候用户会在加载过程中多次点击,我已经添加了一个disabledSubmitButton布尔值,但这完全禁用了提交按钮 - 通过禁用不正确的表单字段模态来破坏用户体验。任何帮助将是非常感激的

以下是我的联系表格HTML

<div class="container section-title-hero text-center msf">
  <h1>Contact Us</h1>
</div>

<div class="container-fluid">
  <div class="container"></div>
</div>

<div class="container-fluid">
  <div class="container">

    <mdb-card class="mt-3 mb-3">

      <mdb-card-body class="px-lg-5 pt-0">
        <div class="row">
          <div class=" msf msfc col mt-3">
            <h5>Send us a message</h5>
          </div>
        </div>

        <form class="text-center" style="color: #757575;" [formGroup]="contactForm" (ngSubmit)="onSubmit()">
          <div style="color: #030A8c !important; padding-bottom: 1em;" class="md-form mt-3">
            <input type="text" formControlName="contactFormName" id="materialContactFormName" class="form-control"
              mdbInput mdbValidate />
            <label for="materialContactFormName">Name</label>
            <mdb-error *ngIf="contactFormName.invalid && (contactFormName.dirty || contactFormName.touched)"><i
                class="fa fa-times" aria-hidden="true"></i>
              Please
              enter your name</mdb-error>
            <mdb-success *ngIf="contactFormName.valid && (contactFormName.dirty || contactFormName.touched)"><i
                class=" fa fa-check" aria-hidden="true"></i>
            </mdb-success>
          </div>

          <div style="color: #030A8c !important; padding-bottom: 1em;" class="md-form">
            <input type="email" formControlName="contactFormEmail" id="materialContactFormEmail" class="form-control"
              mdbInput mdbValidate />
            <label for="materialContactFormEmail">E-mail</label>
            <mdb-error *ngIf="contactFormEmail.invalid && (contactFormEmail.dirty || contactFormEmail.touched)"><i
                class="fa fa-times" aria-hidden="true"></i>
              Please
              enter your email</mdb-error>
            <mdb-success *ngIf="contactFormEmail.valid && (contactFormEmail.dirty || contactFormEmail.touched)"><i
                class=" fa fa-check" aria-hidden="true"></i>
            </mdb-success>
          </div>




          <div style="color: #030A8c !important; padding-bottom: 1em;" class="md-form">
            <input type="text" formControlName="contactFormSubjects" id="materialContactFormSubjects"
              class="form-control" mdbInput mdbValidate />
            <label for="materialContactFormSubjects">Subject</label>
            <mdb-error
              *ngIf="contactFormSubjects.invalid && (contactFormSubjects.dirty || contactFormSubjects.touched)">
              <i class="fa fa-times" aria-hidden="true"></i>
              Please enter a subject</mdb-error>
            <mdb-success
              *ngIf="contactFormSubjects.valid && (contactFormSubjects.dirty || contactFormSubjects.touched)">
              <i class=" fa fa-check" aria-hidden="true"></i></mdb-success>
          </div>


          <div style="color: #030A8c !important; padding-bottom: 1em;" class="md-form">
            <textarea type="text" formControlName="contactFormMessage" id="materialContactFormMessage"
              class="form-control md-textarea" mdbInput mdbValidate></textarea>
            <label for="materialContactFormMessage">Message</label>
            <mdb-error *ngIf="contactFormMessage.invalid && (contactFormMessage.dirty || contactFormMessage.touched)">
              <i class="fa fa-times" aria-hidden="true"></i>
              Please enter a message</mdb-error>
            <mdb-success *ngIf="contactFormMessage.valid && (contactFormMessage.dirty || contactFormMessage.touched)">
              <i class=" fa fa-check" aria-hidden="true"></i></mdb-success>
          </div>

          <!-- <div class="row">
            <div class="col-md-6 mx-auto d-flex justify-content-center">
              <div class="md-form">
                <mdb-checkbox mdbValidate formControlName="contactFormCopy">Send me a copy of this message
                </mdb-checkbox>
                <mdb-error *ngIf="copy.invalid && (copy.dirty || copy.touched)">Input invalid</mdb-error>
                <mdb-success *ngIf="copy.valid && (copy.dirty || copy.touched)">Input valid</mdb-success>
              </div>
            </div>
          </div> -->
          <div class="row">
            <div class="col">
              <button mdbBtn (click)="openModal()" color="info" outline="true" rounded="true"
                class="z-depth-0 my-4 waves-effect" mdbWavesEffect type="submit" [disabled]="disabledSubmitButton">
                Send
              </button>
            </div>
          </div>

        </form>


      </mdb-card-body>

    </mdb-card>
  </div>
</div>
<!--  End Contact Section -->

<app-branch-locations></app-branch-locations>
<!-- Start Branch Locations Section -->



<div class="container">
  <hr>
</div>

这里是联系表的排版稿

import { ConnectionService } from '../../connection.service';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { Component, OnInit, HostListener } from '@angular/core';

// Modals
import { ContactmailmodalComponent } from '../../views/modals/contact/contactmailmodal/contactmailmodal.component';
import { ContactvalidationmodalComponent } from '../../views/modals/contact/contactvalidationmodal/contactvalidationmodal.component';

import { MDBModalRef, MDBModalService } from 'ng-uikit-pro-standard';

@Component({
  selector: 'app-contact',
  templateUrl: './contact.component.html',
  styleUrls: ['./contact.component.scss']
})
export class ContactComponent implements OnInit {





  disabledSubmitButton: boolean = true;
  // Contact Form
  contactForm: FormGroup;
// disabledSubmitButton: boolean = true;
optionsSelect: Array<any>;


modalRef: MDBModalRef;
  constructor(private modalService: MDBModalService, fb: FormBuilder, private connectionService: ConnectionService) {

  this.contactForm = fb.group({
    'contactFormName': ['', Validators.required],
    'contactFormEmail': ['', Validators.compose([Validators.required, Validators.email])],
    'contactFormSubjects': ['', Validators.required],
    'contactFormMessage': ['', Validators.required],
    // 'contactFormCopy': ['', Validators.requiredTrue],
    });
  }

  ngOnInit() {

  this.optionsSelect = [
    { value: 'Feedback', label: 'Feedback' },
    { value: 'Report a bug', label: 'Report a bug' },
    { value: 'Feature request', label: 'Feature request' },
    { value: 'Other stuff', label: 'Other stuff' },
    ];
  }

  get contactFormName() {
    return this.contactForm.get('contactFormName');
  }
  get contactFormEmail() {
    return this.contactForm.get('contactFormEmail');
  }
  get contactFormSubjects() {
    return this.contactForm.get('contactFormSubjects');
  }
  get contactFormMessage() {
    return this.contactForm.get('contactFormMessage');
  }
  // get copy() {
  //   return this.contactForm.get('contactFormCopy');
  // }

  onSubmit() {
    if (this.contactForm.valid) {
      console.log("form submitted");


      this.connectionService.sendMessage(this.contactForm.value).subscribe(

        () => {
          this.disabledSubmitButton = true;
          this.modalRef = this.modalService.show(ContactmailmodalComponent);


        },

        (error) => {
          console.log("Error", error);
        }

      );
    } else {
      // validate all form fields
      this.modalRef = this.modalService.show(
        ContactvalidationmodalComponent
      );
      Object.keys(this.contactForm.controls).forEach((field) => {
        // {1}
        const control = this.contactForm.get(field); // {2}
        control.markAsTouched({ onlySelf: true }); // {3}
      });
    }
  }
  openModal() {

  }
}

先谢谢你

javascript angular typescript forms submit
1个回答
0
投票

我相信禁用和启用按钮根据你在哪一步。你希望它被禁用以防止多次提交,所以禁用它直到请求被发送和模态出现,然后重新启用它。

onSubmit() {
if (this.contactForm.valid) {
  console.log("form submitted");
  this.disabledSubmitButton = true; // disable the button once the onSubmit is triggered

  this.connectionService.sendMessage(this.contactForm.value).subscribe(

    () => {

      this.modalRef = this.modalService.show(ContactmailmodalComponent);
      this.disabledSubmitButton = false; // re-enable the button once the modal shows

    },

    (error) => {
      console.log("Error", error);
      this.disabledSubmitButton = false; // Should re-enable the button if an error occurs aswell 
    }

  );
} else {
  // validate all form fields
  this.modalRef = this.modalService.show(
    ContactvalidationmodalComponent
  );
  Object.keys(this.contactForm.controls).forEach((field) => {
    // {1}
    const control = this.contactForm.get(field); // {2}
    control.markAsTouched({ onlySelf: true }); // {3}
  });
}

}

© www.soinside.com 2019 - 2024. All rights reserved.