避免Angular2通过点击按钮系统地提交表单

避免Angular2通过点击按钮系统地提交表单

本文介绍了避免Angular2通过点击按钮系统地提交表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,可能这个不清楚。获取此表格:

 < form(ngSubmit)=submit()#crisisForm =ngForm> 
< input type =textname =name[(ngModel)] =crisis.name>
< button type =submit>提交< / button>
< button type =button(click)=preview()>预览< / button>
< button type =reset(click)=reset()>重设< / button>
< / form>

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

解决方案

我看到两个解决方案:

1)明确指定 type =button(我认为它是更可取的):

 < button type =button(click)=preview();>预览< / button> 

根据W3规范







使用 $ event.preventDefault()

 < button(click)=preview(); $ event.preventDefault()>预览< / button> 

 < button(click)=preview($ event);>预览< / button> 

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


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

这篇关于避免Angular2通过点击按钮系统地提交表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 23:07