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}`);
}
}
Best Answer
submit
: It is html default form submit event, it will call underlying method when form gets submitted.ngSubmit
: Is host binding situated onform
element. Basically it prevent defaultsubmit
event of browser(which can be formpost
) by returning false. Eventually you can prevent traditionalPostBack
calls or page reload due to form load. This way you can validate your form & submit it to server by manual ajax fromComponent
code