fernando
fernando

Reputation: 717

How to reset a form with required fields in Angular 1.X and Angular Material

It looks like Angular is not clearing the required error message when I call, $setPristine, $setUntouched and $setValidity. However other error messages can clear by simply setting null.

reset() {
    this.form.amount = null;
    this.paymentForm.$setPristine();
    this.paymentForm.$setUntouched();
    this.paymentForm.$setValidity();
  }

Please refer to the plunker https://plnkr.co/edit/boINmB?p=preview

Upvotes: 1

Views: 540

Answers (4)

fernando
fernando

Reputation: 717

I am publishing the answer (possible workaround) to this Angular Material defect. Just add the following style to your project and should fix the problem.

<style>
  .ng-untouched ~ .md-input-messages-animation {
     height: 0;
     opacity: 0;
     transition: height 0.3s, opacity 0.3s;
  }
</style>

Upvotes: 2

Ryan Hamley
Ryan Hamley

Reputation: 2029

You're referencing this.form.amount in your reset function

reset() {
  this.form.amount = null;
  this.paymentForm.$setPristine();
  this.paymentForm.$setUntouched();
  this.paymentForm.$setValidity();
}

... and $ctrl.paymentForm.amount.$error in your HTML.

<div ng-messages="$ctrl.paymentForm.amount.$error" role="alert">
  <div ng-message="required">Field is required</div>
  <div ng-message="dollar">Invalid dollar</div>
  <div ng-message="max">You don't have enough money</div>
  <div ng-message="dailyLimit">Daily payment limit reached</div>
</div>

Change this.form to this.paymentForm and it works:

reset() {
  this.paymentForm.amount = null;
  this.paymentForm.$setPristine();
  this.paymentForm.$setUntouched();
  this.paymentForm.$setValidity();
}

Upvotes: 1

Daniel A. White
Daniel A. White

Reputation: 190907

Just call this.paymentForm.$setPristine(true)

Upvotes: 0

whyyie
whyyie

Reputation: 792

Change this.form.amount = null to this.form.amount = undefined or delete this.form.amount

 reset() {
    delete this.form.amount;
    this.paymentForm.$setPristine();
    this.paymentForm.$setUntouched();
    this.paymentForm.$setValidity();
  }

Upvotes: 0

Related Questions