Angular: Form: page reloads when NgForm removed/restored via NgIf

Created on 1 Feb 2016  路  3Comments  路  Source: angular/angular

Bizarre but arose innocently.

Tried to implement (missing) form reset feature by toggling the previous form out of the DOM and back in with an NgIf pinned to a active flag

<form *ngIf="active" 
          (ngSubmit)="onSubmit()" #heroForm="ngForm">

controlled by component clear method like this

  clear() {
    this.model = new Hero(42, '', '');
    this.active = false;
    setTimeout(()=> this.active=true, 0);
  }

When the form is valid (as it is at the start), clicking clear causes a page reload. If the form is invalid (e.g., no name), there is no reload.

Here's a repro via plunker:
http://plnkr.co/edit/GNhLbONEDHyApCm9vUeh

Most helpful comment

The clear button has the type "submit". So clicking on it causes the form to submit. NgForm is supposed to intercept the submit event, but because NgIf removes the form element from the DOM, the interception does not happen. You can fix it by setting the button type to "button".

All 3 comments

The clear button has the type "submit". So clicking on it causes the form to submit. NgForm is supposed to intercept the submit event, but because NgIf removes the form element from the DOM, the interception does not happen. You can fix it by setting the button type to "button".

Thanks. I did not know that a <button> _without a type attribute_ is the same as a submit button!
That does cure the problem as seen in this revised plunker: http://plnkr.co/edit/u3ltLP84JHn2VkoFKf46?p=preview

Closing this issue and opening #6822 which calls for an explicit reset feature to replace the hack illustrated by this plunker.

This issue has been automatically locked due to inactivity.
Please file a new issue if you are encountering a similar or related problem.

Read more about our automatic conversation locking policy.

_This action has been performed automatically by a bot._

Was this page helpful?
0 / 5 - 0 ratings