简体   繁体   English

避免 Angular2 在按钮点击时系统地提交表单

[英]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 ?为什么所有按钮都会触发submit()函数? And how to avoid that ?以及如何避免这种情况?

I see two options to solve it:我看到两个选项来解决它:

1) Specify type="button" explicitly (i think it's more preferable ): 1)明确指定type="button" (我认为它更可取):

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

According to W3 specification:根据W3规范:

2) Use $event.preventDefault() : 2)使用$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. 这个 Plunker建议否则,每个按钮似乎都按预期工作。

However, to prevent default behaviour of the form you can do this,但是,为了防止表单的默认行为,您可以这样做,


TS: 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您必须从 app.module.ts 中的“@angular/forms”导入 FormsModule

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)我发现 2.0 版本(ngSubmit)正在将一个null事件值传递给该方法,因此您应该我们(submit)

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

your .ts file你的 .ts 文件

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:我发现的解决方法是用a替换button并将按钮样式应用于锚元素:

<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. Angular 为此提供了一个内置的解决方案。 You just need to replace the (submit)="handleSubmit()" with (ngSubmit)="handleSubmit()" .您只需要将(submit)="handleSubmit()"替换为(ngSubmit)="handleSubmit()" By doing this e.preventDefault() will be implicitly called by angular itself under the hood.通过这样做, e.preventDefault()将在引擎盖下由 angular 本身隐式调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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