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 ?

75274 次浏览

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>

这个 Plunker 暗示了另一种情况,每个按钮似乎都按预期工作。

但是,为了防止表单的默认行为,您可以这样做,


TS:

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

模板:

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

我发现在2.0版本中,(ngSubmit)正在向该方法传递一个 null事件值,因此您应该使用 (submit)

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

你的档案

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

我认为有两种解决办法:

1)明确指定 type="button"(我认为它是 更好) :

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

根据 W3规范:

2)使用 $event.preventDefault():

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

或者

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


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

在不希望执行提交的按钮中设置 Type = “按钮”

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

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

角度提供了一个内置的解决方案。您只需将 (submit)="handleSubmit()"替换为 (ngSubmit)="handleSubmit()"即可。通过这样做,e.preventDefault()将被引擎盖下的角本身隐式地调用。