I'm building a form in an Angular 2 application.
Html gives me the submit event. In Angular I could listen to this event using a (submit) event binding. On top of that, Angular adds the ngSubmit event, which I could listen to, using (ngSubmit).
I understand that submit comes from html, and ngSubmit from Angular. What I don't understand is why I would need to listen to a special ngSubmit event, instead of the normal submit event.
I created a plunker that listens to both events and both seem to do the same thing.
What is the difference between listening to (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}`);
}
}
ngSubmit ensures that the form doesn’t submit when the handler code
throws and causes an actual http post request.
from https://blog.thoughtram.io/angular/2016/03/21/template-driven-forms-in-angular-2.html
submit
: It is html default form submit event, it will call underlying method when form gets submitted.
ngSubmit
: Is host binding situated on form
element. Basically it prevent default submit
event of browser(which can be form post
) by returning false. Eventually you can prevent traditional PostBack
calls or page reload due to form load. This way you can validate your form & submit it to server by manual ajax from Component
code
submit: If function is not define on its click event then it never post the data.
(ngsubmit)="saveEmployee(ngForm)": its post the ngform value to console in angular
None of the answers clearly explains as the explaination given in this link.
Submit- triggers a post call to browser URL/server.
Ngsubmit- calls local angular component to do something useful like form validation BEFORE postback to browser url/server.
It can be used to hijack form submission or control submit process.
https://codecraft.tv/courses/angular/forms/submitting-and-resetting/