Avoid Angular2 to systematically submit form on button click

kfa picture kfa · Aug 5, 2016 · Viewed 61.1k times · Source

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 ?

Answer

yurzui picture yurzui · Oct 18, 2016

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