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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38786995/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 21:50:29  来源:igfitidea点击:

Avoid Angular2 to systematically submit form on button click

javascriptformsangularsubmit

提问by kfa

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 ?

为什么所有按钮都会触发该submit()功能?以及如何避免这种情况?

回答by yurzui

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')
}

回答by Ankit Singh

This Plunkersuggests 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">

回答by imal hasaranga perera

I found that with 2.0 release (ngSubmit)is passing a nullevent 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();
}

回答by Arun Ghosh

I has the same issue. The work around I found was the replace buttonwith aand apply button style to anchor element:

我有同样的问题。我周围的工作中发现被替换buttona和应用按钮样式锚元素:

<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>

回答by Alexis Gamarra

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

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

回答by Marouane Afroukh

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
 ],
 })