簡體   English   中英

如何在Angular 1.X和Angular Material中重置包含必填字段的表單

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

當我調用,$ setPristine,$ setUntouched和$ setValidity時,看起來Angular沒有清除所需的錯誤消息。 但是,只需設置null即可清除其他錯誤消息。

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

請參閱plunker https://plnkr.co/edit/boINmB?p=preview

我正在向這個Angular Material缺陷發布答案(可能的解決方法)。 只需將以下樣式添加到項目中即可解決問題。

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

您在重置函數中引用this.form.amount

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

...和HTML中的$ctrl.paymentForm.amount.$error

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

更改this.formthis.paymentForm和它的工作原理:

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

this.form.amount = null更改為this.form.amount = undefineddelete this.form.amount

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

只需調用this.paymentForm.$setPristine(true)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM