Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(ngSubmit) is called when press (click) button

I have two buttons on my Angular2 Form Component. The button are doing their own functionalities.

  1. Button Submit : Which is submit all the values to the API.
  2. Button Add. : Which is push an object to an array.

The two methods are here...

onSubmit() { this.submitted = true; this.model.service_requests = this.modelJobServices; this.onCreateJob(); }  addJobService(modelJobService :Jobservice){ let modelJobServiceLocal = new Jobservice(modelJobService.service_id,modelJobService.service_note,modelJobService.status) this.modelJobServices.push(modelJobServiceLocal); } 

My Component.html structure is as below

<form #jobRegistrationForm="ngForm" (ngSubmit)="onSubmit()"> ...... ...... ...... <button class="flat btn-primary form-control" id="btn_add" (click)="addJobService(modelJobService)"> ADD SERVICE </button> .... .... .... <button (submit)="onSubmit()" [disabled]="!jobRegistrationForm.form.valid" class="flat form-control col-md-4 btn-primary">{{BUTTON_TEXT}}</button> 

when I press the (click) button the form is submitted to the API call. But I did not call the onSubmit() on the (click) button event

like image 903
nifCody Avatar asked Dec 05 '16 06:12

nifCody


People also ask

What is ngSubmit?

Definition and Usage The ng-submit directive specifies a function to run when the form is submitted. If the form does not have an action ng-submit will prevent the form from being submitted.


2 Answers

Buttons inside a form become a type="submit" by default.

Make them plain buttons explicitly:

<button type="button" 
like image 132
Günter Zöchbauer Avatar answered Sep 21 '22 18:09

Günter Zöchbauer


As per W3 spec the default value for attribute type inside button is submit.

ie <button> == <button type="submit">

If you dont want the ngSubmit event to get triggered set the attribute type to button.

<button type="button">

Or use $event.preventDefault().

<button (click)="addJobService(modelJobService); $event.preventDefault()"

like image 39
arun kumar Avatar answered Sep 22 '22 18:09

arun kumar