Avoid Angular2 to systematically submit form on button click Avoid Angular2 to systematically submit form on button click angular angular

Avoid Angular2 to systematically submit form on button click


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


This Plunker suggests otherwise, every button seem to work as intended.

However, to prevent default behaviour of the form you can do this,


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

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