What could be causing Angular 8 form to be submitted multiple times?

I am a beginner when it comes to Angular. I have created a form with the following structure:

<h2>Login</h2>
<form [formGroup]="loginForm" (ngSubmit)="onSubmit()">
    <div class="form-group">
        <label for="username">Username</label>
        <input type="text" formControlName="username" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.username.errors }" />
        <div *ngIf="submitted && f.username.errors" class="invalid-feedback">
            <div *ngIf="f.username.errors.required">Username is required</div>
        </div>
    </div>
    <div class="form-group">
        <label for="password">Password</label>
        <input type="password" formControlName="password" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.password.errors }" />
        <div *ngIf="submitted && f.password.errors" class="invalid-feedback">
            <div *ngIf="f.password.errors.required">Password is required</div>
        </div>
    </div>
    <div class="form-group">
        <button [disabled]="loading" class="btn btn-primary">
            <span *ngIf="loading" class="spinner-border spinner-border-sm mr-1"></span>
            Login
        </button>
    </div>
</form>

Upon clicking the button, the form gets submitted multiple times.

What could be causing this issue and how can I fix it?

Any help would be greatly appreciated.

Thank you

Answer №1

Do you know what to expect? The onSubmit function will be executed every time the form is submitted.

If you want the form to only submit when it is valid, then use

(ngSubmit)="f.valid && onSubmit()"

Alternatively, if you want the form to submit only once, you can set a submitted flag

(ngSubmit)="!submitted && onSubmit()"

And in your component file, add:

submitted = false;
onSubmit() {
  this.submitted = true;
}

Answer №2

To update your form, simply delete the

(ngSubmit)="onSubmit()"
from the form and instead attach a Click event to your button as shown below:

<button [disabled]="loading" class="btn btn-primary" (click)="onSubmit()">
  <span *ngIf="loading" class="spinner-border spinner-border-sm mr-1"></span>
  Login
</button>

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

Error: Null value detected while trying to access the property 'appendChild'

Can anyone help me with this error? Uncaught TypeError: Cannot read property 'appendChild' of null myRequest.onreadystatechange @ script.js:20 Here's the code snippet where I'm facing the issue // index.html <html> <he ...

Ways to manage properties that are non-existent

Whenever vm8 encounters a property that doesn't exist, it will display an error message like this: Cannot read property 'value' of null. For example, when passing an id that doesn't exist: var pass = document.getElementById('pass ...

How can I invoke a jQuery widget's public method from the outside using the plugin reference?

I have encountered an issue with a plug-in popup that I created. I am attempting to reference and access the public method of the plug-in, but I am receiving an 'Undefined Function' error. var pop = $('.divCls').popup(); pop.setTit ...

NodeJs guide on removing multiple documents from a MongoDB collection using their _id values

Consider the following array of _ids: ["a12s", "33qq", "121a"] In MongoDB, there are methods such as deleteMany, which allows deletion based on specific queries: var myquery = { address: 'abc' }; dbo.collection("customers").deleteMany(myque ...

Is there a way to utilize JQuery to identify and update the contents of a specific element?

My current structure is as follows: <div class="button"> <a href="/" target="_blank" class="test">Photos</a> </div> How can I use JQuery to select .button and remove the target="_blank" attribute from the html? I managed to reac ...

Tips for integrating Material-Ui Autocomplete with Formik's Field component to create Multi-Select check boxes

Trying to integrate Formik's Field component with Material-Ui Autocomplete for multiple values that include checkboxes has been challenging. Whenever a value is selected from the dropdown list, the popup closes and needs to be reopened for the next se ...

Is it possible to extend the Object class in order to automatically initialize a property when it is being modified?

My experience with various programming languages leads me to believe that the answer is likely a resounding no, except for PHP which had some peculiar cases like $someArray['nonexistentKey']++. I'm interested in creating a sparse object whe ...

Utilizing HighChart in ASP.NET MVC for Dynamic Data Visualization from a Database

I am completely new to ASP.NET MVC and I am trying to show data from a database in a Highchart using Visual Studio 2015. In my controller, I have the following code to retrieve data from the database: namespace HelloWorld.Controllers { public class Se ...

Issue encountered: Django Rest Framework functionality fails to execute properly when accessed from varying URLs

I'm currently immersed in the tutorial found at: http://www.django-rest-framework.org/ as I endeavor to construct a restful API for my django application, which is being hosted on apache. My ultimate goal is to utilize ajax in order to call the API an ...

Unlock the power of Javascript in Wordpress by converting a string into a dynamic Page Title

Imagine having a custom-coded menu of links that needs to be added to multiple Wordpress pages. The menu is consistent across all pages, except for the variable part of the link text enclosed in square brackets. Here is how the HTML structure looks: <l ...

When using Typescript, ENUMs can be passed as interface values without any issues. However, errors may occur

To ensure consistency in sizes and colors within my UI library, I decided to create an ENUM for each value. export enum sizes { small = 'small', medium = 'medium', large = 'large', } export enum colors { orange = ...

What is the best way to send data to a component without using props for testing purposes?

Currently, I am evaluating a component that lacks props but relies on data from context for its fulfillment. Here is the code snippet of the component in question: export const MyComponent: FC = () => { const { arrayOfObjects } = useFn() return ar ...

If a 401 response is encountered in Next.js, automatically navigate to the login page

In my project, I utilize Next JS middleware to handle redirection to the login page if there is no token available in middleware.ts: import type { NextRequest, NextResponse } from "next/server"; export function middleware(request: NextRequest, r ...

Explore by the anchor tag

I've recently implemented a search bar utilizing Bootstrap. This is the code for the search bar: <div class="md-form mt-0"> <input class="form-control" id="myInput" type="text" placeholder="Sear ...

Accessing and displaying all states in $stateProvider using AngularJS and ui-router

Here's a simple question: how can I find all instances of $stateProvider.state in my app.js, which is my AngularJS config file? In the past with ngRoute, I could achieve this by using a similar approach in my .run() block: .run(function ($route) { ...

What is the best way to adjust the size of an Angular Material Slider?

I'm attempting to insert a slider into my program, but the slider is displaying as too lengthy for the designated space. I'm curious if there's a straightforward method of adjusting its length to fit better within the container. So far, I&a ...

Can you identify this pattern: .on('eventName', function(){...});?

Do you recognize the .on('eventName', function(){...}); pattern commonly used in jQuery, socket.io, peerjs, and other libraries for event handling? What is this pattern formally called? I am interested in understanding the underlying structure, ...

Which costs more, using an undefined ng-bind or both ng-bind and ng-show together?

Assuming that toShowVar is undefined, which of these options would be more costly? <span ng-bind="toShowVar" ng-show="toShowVar"></span> or <span ng-bind="toShowVar"></span> The latter option would clearly not display anything o ...

Dead keyup event using jQuery live in SignalR invocation

I am working on a sample chat application using SignalR, but I'm facing an issue with my keyup event not functioning properly. Below is the code snippet: // Keyup event for text box $(".ChatText").on('keyup', function () { if($(".ChatTe ...

The specified variable will not be visible in the window object

I recently created a JavaScript code snippet that looks like this: let var1 = 1; window.var2 = 2; After running the code in the Chrome console, I entered window to inspect the global window object. Surprisingly, only the second variable appeared and the ...