Angular 2 ngSubmit triggers unexpectedly on occasions when it is not supposed to

Currently, I am working on developing an Ionic 3 application with Angular 2 and TypeScript. In the app, there is a form that is responsible for sending data to our server. The issue I am facing is that whenever I click on the following button:

<button ion-button color="nice" small (click)="selectedDate = tomorrow">Tomorrow</button>

the form automatically submits the data. Can anyone point out what mistake I might be making?

Here is the form structure:

 <form [formGroup]="reservateForm" (ngSubmit)="submitReservateForm()">
              <ion-row>
                <ion-col col-12>
                  <p>Reserve a table. Your reservation will be confirmed by the restaurant.</p>
                  <br>
                  <h3>How many people are coming?</h3>
                  <ion-range min="1" max="16" mode="md" snaps="true" pin="true" step="1" formControlName="speople">
                    <ion-label range-left>1</ion-label>
                    <ion-label range-right>16</ion-label>
                  </ion-range>
                  <br>
                </ion-col>
                <ion-col col-12>
                  <div class="fast-dial">
                    <button ion-button color="nice" small (click)="selectedDate = tomorrow">Tomorrow</button>
                    <button ion-button color="nice" small (click)="selectedDate = theDayAfter">Day after Tomorrow</button>
                  </div>
                </ion-col>
              </ion-row>
              <ion-row>
                <ion-col col-6>
                  <ion-item formControlName="sdate" ngDefaultControl (click)="showDatePicker()">
                    {{selectedDate || "No date selected"}}
                  </ion-item>
                </ion-col>
                <ion-col col-6>
                  <ion-item formControlName="stime"  ngDefaultControl (click)="showTimePicker()">
                    {{selectedTime || "No time chosen"}}
                  </ion-item>
                </ion-col>
              </ion-row>
              <ion-row>
                <ion-col col-12>
                  <ion-item>
                    <ion-label stacked>Full Name</ion-label>
                    <ion-input formControlName="sname"></ion-input>
                  </ion-item>
                </ion-col>
                <ion-col col-12>
                  <ion-item>
                    <ion-label stacked>Your Email</ion-label>
                    <ion-input formControlName="semail" type="email"></ion-input>
                  </ion-item>
                </ion-col>
                <ion-col col-12>
                  <ion-item>
                    <ion-label stacked>Phone Number</ion-label>
                    <ion-input formControlName="sphone" type="number"></ion-input>
                  </ion-item>
                </ion-col>
                <ion-col col-12>
                  <ion-item>
                    <ion-label stacked>Comments</ion-label>
                    <ion-textarea formControlName="snotes"></ion-textarea>
                  </ion-item>
                </ion-col>
                <ion-col col-12>
                  <button type="submit" [disabled]="!reservateForm.valid" ion-button color="nice">Submit</button>
                </ion-col>
              </ion-row>
            </form>

Here is my TypeScript code related to this functionality:

    constructor(public navCtrl: NavController, public modalCtrl: ModalController, public http: Http, public navParams: NavParams, private alertCtrl: AlertController,
        private photoViewer: PhotoViewer, public platform: Platform, private datePicker: DatePicker,
        private formBuilder: FormBuilder) {
        this.reservateForm = this.formBuilder.group({
          speople: ['', Validators.required],
          sdate: ['', Validators.required],
          stime: ['', Validators.required],
          sname: ['', Validators.required],
          semail: ['', Validators.required],
          sphone: ['', Validators.required],
          snotes: ['', Validators.required]

        });
      }

submitReservateForm() {
    let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
    let options = new RequestOptions({ headers: headers });

    let postParams = {
      location_id: this.navParams.get('id'),
      name: this.reservateForm.value.name,
      email: this.reservateForm.value.email,
      phonenumber: this.reservateForm.value.phone,
      people: this.reservateForm.value.people,
      comments: this.reservateForm.value.notes,
      date:this.reservateForm.value.date,
      time: this.myTime
    }

    this.http.post(AppSettings.BASE_URL + "api/postBooking", postParams, options)
      .subscribe(data => {
        console.log(data);
      }, error => {
        console.log(error);
      });

    // Go back to first Tab
    this.query = 'slide1';
  }

I suspect that all buttons in the form are being treated as submit buttons which triggers the function. How can I go about addressing this issue?

Answer №1

Specify the type of the button as button, by default it is set to submit within a form

<button type="button" ion-button color="nice" small (click)="selectedDate = tomorrow">Tomorrow</button>

Answer №2

Ensure that every button on your page includes the type attribute. Any button that is not meant to submit a form should have type="button". The button you designate for submitting the form must have type="submit".

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

Unable to perform multi-delete action upon clicking the checkbox button as intended

Within my GridView, I have implemented a Multi-delete feature. Below is the code snippet for your reference:- <script type="text/javascript> function ValidateAll() { var chkselectcount = 0; var gridview = document.getElementById( ...

Unable to initiate the server generated by the express.js generator

Currently, I am trying to set up an Express.js server using their generator. Following the documentation, I was able to successfully create the basic structure. However, when attempting to run the prescribed command (SET DEBUG=transcriptverificationserver: ...

Utilizing external clicks with Lit-Elements in your project

Currently, I am working on developing a custom dropdown web component using LitElements. In the process of implementing a feature that closes the dropdown when clicking outside of it, I have encountered some unexpected behavior that is hindering my progres ...

Bootstrap not being recognized in AngularJS HTML

I've been working on learning AngularJS, but unfortunately I can't seem to get any Bootstrap themes to show up in my web application. Here is the HTML code for the header that I've been trying: <nav class="navbar navbar-default"> ...

Create a filtering feature with Django RestFramework and an Angular front-end

Can someone assist me in building a filter for my Angular frontend that connects to a Django backend using restframework_filter? I have the following code in my backend: viewset.py from snippets.models import Snippet from .serializers import SnippetSeria ...

Guide to automatically filling in a form's fields with information from a database by clicking on a link

Currently, I have a form in HTML that is designed to gather user/member information. This form connects to a database with multiple columns, with two key ones being "user_email" and "invoice_id". Upon the page loading, the input for "user_email" remains hi ...

Querying the field's object type in MongoDB

My database contains records with a field that has different data types in each record. I would like to query only for the records where this field contains strings. Is there a way to search for specific data types in this field? {"field1":ObjectId("53de" ...

Is it possible for the Redux state to become unsynchronized?

const SortingFunction = ({ dataState, updateState }) => { const handleClick = () => { const newState = JSON.parse(JSON.stringify(dataState)) // Make necessary updates to the new state based on the current dataState updateState(newStat ...

What might prevent an onSubmit event from triggering the execution of "checkTheForm()"?

Despite consuming a substantial amount of information on the internet, I still find myself puzzled by why my code isn't functioning as expected. I acknowledge that there are numerous tutorials out there guiding me to use <form action="index.html" o ...

tilt and give motion to image within canvas

I am looking to incorporate skewing and animation effects on an image displayed on a canvas. While I have successfully drawn the image on the canvas using the code snippet below, I am unsure about how to apply skewing and animation to the image post-drawin ...

Struggling with textpath SVG elements in jQuery

Currently, I am implementing SVG in my project and aiming to apply the toggleClass function using jQuery on the textpath elements upon clicking. My initial plan was: $("text#names > textpath").click(function() { $(this).toggleClass("newClass"); }) ...

Experiencing code coverage challenges in Angular 8 relating to function properties

https://i.sstatic.net/WQpVB.png Looking for suggestions on how to create a unit test case in Jasmine to address the code coverage problem. Any ideas? ...

Generic Abstract Classes in TypeScript

In my TypeScript code, I have an abstract generic class with a method that takes a parameter of a class type variable. When I tried to implement the abstract method in a derived class, I noticed that the TypeScript compiler doesn't check the type of t ...

What is the best way to create a sharp light effect on a sphere in three.js?

My three.js scene features a sphere and directional light. The sphere appears to gradually darken as you look at it. How can I speed up the transition from light to dark? Is there a way to make the light appear "sharper"? var scene, camera, renderer, co ...

Transform a text string into JSON format using Javascript

I need help converting a text string to JSON format using JavaScript. The text string is as follows: workingtable;AB8C;book_id;7541; I want to convert it into JSON format like this: {"workingtable":"AB8C","book_id":"7541"} Is there a specific JSON funct ...

Deactivate background hover effects for bar charts in Recharts

Is there a way to disable the gray background that appears when hovering over bar charts in Recharts? I'm using version 1.4.1 and my code looks like this: import React from "react" // Recharts import { Bar, BarChart, CartesianGrid, ResponsiveContain ...

Issue encountered while subscribing to SalesForce topic using Node.js

Attempting to subscribe to a SalesForce topic through a Node.js server using the code provided in the JSForce documentation: conn.streaming.topic("InvoiceStatementUpdates").subscribe(function(message) { console.log('Event Type : ' + message.ev ...

Keeping firebase auth while removing firestore from Vue project

I have recently made the switch from Firestore to MongoDB, and I am currently in the process of removing references to Firestore in my App.vue file. However, I am still utilizing Firebase authentication. Upon checking the console error message, I came acr ...

Intercontinental partnership bridging two separate entities

Within my application, there is a primary module: app.component.html <h1>{{globals.title}}</h1> <router-outlet></router-outlet> In app.module.ts @NgModule({ imports: [ BrowserModule, HomeModule, NotesModule, ...

Switching to '@mui/material' results in the components failing to render

I have a JavaScript file (react) that is structured like this: import { Grid, TextField, makeStyles } from '@material-ui/core' import React from 'react' import {useState} from 'react' //remove this function and refresh. see ...