When using a ngForm, submitting the form is triggered each time an action button is clicked

I have a form with multiple buttons in my ngForm. Each button has a different action, such as changing the status used for *ngIf condition check. However, every time I click the Create or Upload button, the form is submitted again and a new record is created in the database.

I have tried changing the click event to onClick as suggested in other answers, but the issue persists. Can someone please help me by reviewing the code below?

<form #adsForm="ngForm" (submit)="onSubmit()">
    <table  class="table createAds text-center">
      <thead>
      ......
      </thead>
      <tbody>
        <tr class="border_bottom">
          <td class="align-middle"><span style="color: red;">inactive</span></td>
          ......
          <td class="align-middle" *ngIf="!paying && !created">
            <button [disabled]="months === undefined" 
              class="btn btn-outline-primary" type="submit">Create
            </button>
          </td> 
          <td class="align-middle" *ngIf="created">
            <button [disabled]="imageCount == 0" class="btn btn-outline-primary" (click)="confirmToPay()">Pay
            </button>
          </td>          
          <td class="align-middle" *ngIf="!paying && !created">
            <button class="btn btn-outline-primary" (click)="onCancel()">Cancel</button>
          </td> 
          <td class="align-middle" *ngIf="created">
            <button class="btn btn-outline-primary" (click)="onUpload()">Upload</button>
          </td>          
        </tr>
      </tbody>
    </table>
  </form>

onSubmit() {   
    let data = new AdsToCreate();
   ......   

    this.memberService.createAds(data).subscribe(resp => {
      this.getUserAds();  
      this.created = true; 
    }, error => {
      console.log(error);
    });  
  }
  
 confirmToPay() {
    this.confirming = true;    
  }
  
 onCancel() {
    this.requesting = true;
    this.paying = false;
    this.checking = false;
    this.created = false;    
  }
  
 onUpload() {
    this.uploading = true;
  }

Answer №1

This situation is odd, consider removing the (submit) event handler from the form element.

<form #adsForm="ngForm">

Then, eliminate the type="submit" attribute from this button and replace it with the (click) event handler:

<button [disabled]="months === undefined" 
              class="btn btn-outline-primary" (click)="onSubmit()">Create
            </button>

Alternatively,

You may want to explicitly specify the type="button" for all other buttons.

<form #adsForm="ngForm" (submit)="onSubmit()">
    <table  class="table createAds text-center">
      <thead>
      ......
      </thead>
      <tbody>
        <tr class="border_bottom">
          <td class="align-middle"><span style="color: red;">inactive</span></td>
          ......
          <td class="align-middle" *ngIf="!paying && !created">
            <button [disabled]="months === undefined" 
              class="btn btn-outline-primary" type="submit">Create
            </button>
          </td> 
          <td class="align-middle" *ngIf="created">
            <button type="button" [disabled]="imageCount == 0" class="btn btn-outline-primary" (click)="confirmToPay()">Pay
            </button>
          </td>          
          <td class="align-middle" *ngIf="!paying && !created">
            <button type="button" class="btn btn-outline-primary" (click)="onCancel()">Cancel</button>
          </td> 
          <td class="align-middle" *ngIf="created">
            <button type="button" class="btn btn-outline-primary" (click)="onUpload()">Upload</button>
          </td>          
        </tr>
      </tbody>
    </table>
  </form>

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

The component prop of Typography in TypeScript does not accept MUI styling

Working with MUI in typescript and attempting to utilize styled from MUI. Encountering an error when passing the component prop to the styled component. The typescript sandbox below displays the issue - any suggestions for a workaround? https://codesandbo ...

What steps can be taken to resolve the issue "AG Grid: Grid creation unsuccessful"?

For my project, I decided to use the modular import approach for AG-Grid. This means importing only the necessary modules instead of the entire package: "@ag-grid-community/core": "31.3.2", "@ag-grid-community/react": ...

Angular: Navigating to a distinct page based on an API response

In order to determine which page to go to, based on the response from an API endpoint, I need to implement a logic. The current API response includes an integer (id) and a string (name). Example Response: int: id name: string After making the API call, I ...

How to dynamically load a component in Angular 2 using a string argument

I am currently developing an app that performs static analysis on components from an Angular application and then renders them within another Angular app. This app serves as a comprehensive style guide with detailed information on inputs and other key aspe ...

Trouble arises when managing click events within the Material UI Menu component

I've implemented the Menu Component from Material UI as shown below - <Menu open={open} id={id} onClose={handleClose} onClick={handleClick} anchorEl={anchorEl} transformOrigin={{ horizontal: transformOriginRight, vertical: t ...

The Angular CLI has encountered an issue - Syntax Error: Unexpected token {

After using Angular CLI to successfully create projects for some time, I encountered an issue today when attempting to serve a new project. ng serve Unexpected token { SyntaxError: Unexpected token { at exports.runInThisContext (vm.js:53:16) at Modu ...

Firestore TimeStamp.fromDate is not based on UTC timing

Does anyone have a solution for persisting UTC Timestamps in Firestore? In my Angular application, when I convert today's date to a Timestamp using the code below, it stores as UTC+2 (due to summer time in Switzerland). import {firebase} from ' ...

Strategies for modifying the title attribute within an <a> tag upon Angular click event

I am attempting to dynamically change the title attribute within an anchor tag upon clicking it. The goal is for the title attribute to toggle between two states each time it is clicked. Currently, I am able to change the title attribute successfully upon ...

What is the process of downloading dependencies with the command 'npm install'?

Upon navigating to the folder containing my package.json file for an Angular app, I noticed that when I run the command npm install, it takes a considerable amount of time (around 10 minutes) to download just 6 dependencies. After completion, it download ...

Refreshing the page is the only way to see the changes made by Angular's delete item function reflected

In my application, I am retrieving a table of users from an API. However, when I delete a user, the table does not update until I manually reload the page. This relates to the user service in my application. getUsers(): Observable<any> { return ...

What is the best way to retrieve app.state in a Remix project when running a Cypress test?

One way Cypress can expose an app's state to the test runner is by using the following approach in React: class MyComponent extends React.Component { constructor (props) { super(props) // only expose the app during E2E tests if (window.C ...

Two forms are present on one page, but the submit button is triggering validations for both forms simultaneously

Currently, I am facing an issue with two forms that share one submit button. The problem is that although I have implemented validation for both forms, the validations are not working separately. I want the validations to work independently - when I submit ...

Issue TS2345: Cannot use type 'Product | undefined' as an argument for type 'Product[] | PromiseLike<Product[]>'

Having trouble retrieving my products using their IDs You can find the code here ...

Step-by-step guide to setting up Next.js with TailwindCSS using JavaScript explicitly

Currently, I am working on a Next.js project where all the files have the extension .tsx (TypeScript). Although TypeScript is similar to Java, I prefer to have the file ending as .js. I attempted to modify the command (npx create-next-app -e with-tailwin ...

Is it possible to initiate a request action in both the constructor and ngOnInit method?

I am facing a situation where I need to trigger a request action from both the constructor and ngOnInit functions in order to load data. However, I have noticed that on the second call, one of the dispatch actions is not being invoked and the data remains ...

Set up Nginx to host Angular static files and act as a reverse proxy for express

Recently, I've started using Nginx for serving static Angular files and proxying to a backend Express server. Both the frontend (with Nginx) and backend are dockerized. My frontend consists of a button that makes a request to fetch data from Express. ...

Angular not successfully passing ID in for loop

I am trying to pass the res[i].id value to my ArrayList while maintaining the sequence. Can anyone help me understand why 809 and 806 are not getting added to the arrayList correctly? 0: {id: 0, ArrayListID: 809, VarName: "TEST001A"} 1: {id: 0, ...

Angular 13 and Tailwind CSS: A Match Made in Web

After attempting to run : ng add @ngneat/tailwind An unexpected error occurred: NOT SUPPORTED: keyword "id", please use "$id" for schema ID !!!!!! This took place in VSCode. Versions: Angular cli v: 13.1.2 npm v: 8.3.0 ...

Is there a way to customize Material UI theme types and make adjustments to existing types using Typescript?

One way to customize the material ui theme is by extending its type and adding new properties, as shown here: For example, if we want to add an appDrawer property, it can be done like this: declare module '@material-ui/core/styles/createMuiTheme&apos ...

What is the Time and Location of the Angular CLI Installation on the Local Machine?

Once I installed Node.js, I proceeded to import an Angular project from GitHub into VSCode. Next, I executed the following commands in sequence: npm install //This command created the node_modules folder, but unfortunately, I still do ...