ng-submit event is called twice in the Angular 2

2019-09-18 12:11发布

问题:

The method is called twice When the ng-submit event occurring in Angular 2. How do I make a call method only once? Why does method calls twice in the angular 2?

import { Component } from '@angular/core';

@Component({
  moduleId: module.id,
  selector: 'app-form-ngform',
  template: `
    <form (ngSubmit)="onSubmit()">
      <button type="submit" class="btn btn-default">Submit</button>
    </form>
`
})
export class FormNgformComponent {
  onSubmit() {
    alert('test');  
   }
}

回答1:

Probably another duplicate of this:

Angular 2 Form Getting Duplicated?

Make sure you are bootstrapping your app like this:

import {disableDeprecatedForms, provideForms} from '@angular/forms';

bootstrap(AppComponent, [
   disableDeprecatedForms(),
   provideForms()
]);


回答2:

Updating the solution as disableDepricatedForms and provideForms are deprecated as per to angular version 2.0.0.rc6.

forms: deprecated provideForms() and disableDeprecatedForms() functions have been removed. Please import the FormsModule or the ReactiveFormsModule from @angular/forms instead.

see: https://github.com/angular/angular/compare/2.0.0-rc.5...2.0.0-rc.6