Angular – Difference between angular submit and ngSubmit events

angular

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 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

Related Topic