Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid Angular2 to systematically submit form on button click

People also ask

How do I stop form button from submitting?

The simplest solution to prevent the form submission is to return false on submit event handler defined using the onsubmit property in the HTML <form> element.

How do you submit form only once after multiple clicking on submit?

onsubmit = function () { if (allowSubmit) allowSubmit = false; else return false; } })(); (well, as sure-fire as you can get with JS enabled anyway). You could disabled the button as a visual confirmation to the end user that the form can only be submit once too. Very correct.

Can I submit form with Button?

You can tie a submit button to a form that the button doesn't live inside of. The trick is to give the form an id and then reference that id with the button's form property. With this setup, clicking the Submit button will cause the form to be submitted.


I see two options to solve it:

1) Specify type="button" explicitly (i think it's more preferable):

<button type="button" (click)="preview();">Preview</button>

According to W3 specification:

  • http://w3c.github.io/html-reference/button.html

    A button element with no type attribute specified represents the same thing as a button element with its type attribute set to "submit".

2) Use $event.preventDefault():

<button (click)="preview(); $event.preventDefault()">Preview</button>

or

<button (click)="preview($event);">Preview</button>

preview(e){
  e.preventDefault();
  console.log('preview')
}

This Plunker suggests otherwise, every button seem to work as intended.

However, to prevent default behaviour of the form you can do this,


TS:

submit(e){
 e.preventDefault();
}

Template:

<form (submit)="submit($event)" #crisisForm="ngForm">

You have to import FormsModule from '@angular/forms' in your app.module.ts

import { FormsModule } from '@angular/forms';
 @NgModule({
  imports: [
    FormsModule
 ],
 })

I found that with 2.0 release (ngSubmit) is passing a null event value to the method so instead you should us (submit)

<form (submit)="submit($event)" #crisisForm="ngForm">

your .ts file

submit($event){
   /* form code */
   $event.preventDefault();
}

Set type="button" in the button that you don't want to execute submit.