Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between (click) and (ngSubmit) in Angular 2

Tags:

angular

In submitting a form in Angular 2 I have gotten two patterns to work.

<form (ngSubmit)="pathSave()" #fDoc="ngForm">
  ( bunch of form fields ) 
  <div class="form-group">
    <button type="submit" class="btn btn-primary">Save</button>
  </div>
</form>

versus

<form #fDoc="ngForm">
  ( bunch of form fields ) 
  <div class="form-group">
    <button class="btn btn-primary" (click)="pathSave()">Save</button>
  </div>
</form>

The difference being where the Component's action method is called. Is there an advantage of one pattern over the other?

like image 324
AlanObject Avatar asked May 10 '17 17:05

AlanObject


People also ask

What is the difference between ng-click and Ng-submit?

3 ng-submit associated with forms, this event fires when u submit form. Where as ng-click can work without form submit event Share Follow answered May 8 '14 at 22:04

What does ngsubmit do in HTML?

The ngSubmit directive binds to the submit eventin the browser, which is fired when a form is submitted. From MDN: Note that submit is fired only on the form element, not the button or submit input. (Forms are submitted, not buttons.)

What is ng-change and Ng-click in AngularJS?

The ng-change directive tells AngularJS what to do when the value of an HTML element changes. The ng-click directive tells AngularJS what to do when an HTML element is clicked. This might sound unconventional, but hands down I’d go with blue-chip art. A Basquiat painting soared 2,209,900% when it was bought for $5,000 and sold for $110,500,000.

What is onClick event in Angular 2?

One feature is the ability to call a function with the help of an onClick event in Angular 2. The Angular 2 event system can be used to handle different types of events, such as mouse clicks, keyboard presses, and touch gestures. The onclick event triggers an event or function when a user clicks on a component or an element.


1 Answers

There is no (onclick) event, only (click).

The difference is that (ngSubmit) listens to the ngSubmit event of the NgForm directive and click to the click event of the <button> element.

The button in the 2nd example will cause the submit event which also causes the ngSubmit event, but because it is not listened to, it will have no effect.

In your examples there is no difference in the behavior though.

like image 176
Günter Zöchbauer Avatar answered Oct 13 '22 23:10

Günter Zöchbauer