简体   繁体   中英

Avoid Angular2 to systematically submit form on button click

Ok so maybe this is unclear. Get this form:

<form (ngSubmit)="submit()" #crisisForm="ngForm">
   <input type="text" name="name" [(ngModel)]="crisis.name">
   <button type="submit">Submit</button>
   <button type="button" (click)="preview()">Preview</button>
   <button type="reset" (click)="reset()">Reset</button>
</form>

Why do all buttons trigger the submit() function ? And how to avoid that ?

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:

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();
}

I has the same issue. The work around I found was the replace button with a and apply button style to anchor element:

<form (ngSubmit)="submit()" #crisisForm="ngForm">
   <input type="text" name="name" [(ngModel)]="crisis.name">
   <button type="submit">Submit</button>
   <a class="btn" (click)="preview()">Preview</a>
   <a class="btn" (click)="reset()">Reset</a>
</form>

在不想执行提交的按钮中设置type="button"

Angular provide a built-in solution for this. You just need to replace the (submit)="handleSubmit()" with (ngSubmit)="handleSubmit()" . By doing this e.preventDefault() will be implicitly called by angular itself under the hood.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM