Difference between angular submit and ngSubmit events?

I am creating a form in an Angular 2 application.

Html gives me a send event. In Angular, I could listen to this event using the event binding (submit). In addition, Angular adds an ngSubmit event that I could listen using (ngSubmit).

I understand that submit comes from html and ngSubmit from Angular. I don’t understand why I will need to listen for the ngSubmit special event, and not the normal send event.

I created a plunker that listens for both events, and both seem to do the same.

What is the difference between listening (submit) and (ngSubmit)?

@Component({ selector: 'my-app', template: ` <form (submit)='onSubmit(form)' (ngSubmit)='onNgSubmit(form)' novalidate #form='ngForm'> <input type='text' name='input' [(ngModel)]='input' required> <input type='submit' value='Submit' required> </form> `, }) export class App { input : string; onSubmit(form): void { console.log(`submit: ${this.input}, valid: ${form.valid}`); } onNgSubmit(form): void { console.log(`ng-submit: ${this.input}, valid: ${form.valid}`); } } 
+8
angular
source share
2 answers

ngSubmit ensures that the form is not submitted when the handler code throws and calls the actual HTTP request.

from https://blog.thoughtram.io/angular/2016/03/21/template-driven-forms-in-angular-2.html

+5
source share

submit . This is the default html form submit event, it will call the base method when the form is submitted.

ngSubmit : Is the host binding located on the form element. Basically this is to prevent the default submit event (which may be post ) by returning false. In the end, you can prevent traditional PostBack calls or page reloads due to form loading. This way you can validate your form and submit it to the server manually ajax from Component code

+2
source share

All Articles