【问题标题】:how to clear validation errors for mat error after submitting the form提交表单后如何清除mat错误的验证错误
【发布时间】:2020-02-12 08:53:37
【问题描述】:

提交表单后,我无法清除 mat 错误的验证错误。我在提交后通过 form.resetForm() 重置表单,但我仍然无法清除 mat 错误的验证。我也尝试重新初始化表单。你能帮忙吗?提前致谢。

这里是code

【问题讨论】:

  • 你在用ngForm吗?
  • 我尝试使用 ngForm 但我仍然无法清除验证@Mridul
  • 提供 stackblitz 编辑 url。
  • 提供@Mridul
  • 检查并做出相应的更改

标签: angular angular-material


【解决方案1】:

使用ngForm从此处获取参考

In your Html file

<form  fxFlex fxLayout="column" fxLayoutGap="10px" [formGroup]="noteForm" #noteForm="ngForm">

In your ts file

 @ViewChild('noteForm', { static: true }) noteForm: NgForm;
//to reset form
this.noteForm.resetForm();

在您的 HTML 和 TS 文件中相应地替换名称。

【讨论】:

  • 谢谢,但它不起作用。验证错误正在清除,但表单未完全清除,我在控制台中收到验证错误。
  • 似乎问题出在您的validationService 上。请检查
  • JuNe 的回答对我有用。感谢您花时间帮助我 :) @Mridul
【解决方案2】:

您不需要ngForm。您可以简单地将控件的错误设置为null。

onSubmitchngPwd() {
    this.changepwdform.get("currentpassword").setErrors(null);  // set errors to null
}

示例:https://stackblitz.com/edit/angular-en6coj

【讨论】:

  • 它非常适合我。非常感谢你。 @JuNe
【解决方案3】:

在材料设计中,ma​​t-errors 会在控件被触摸或变脏时触发,因此我们需要在重置表单后将它们标记为未触摸控件 以下是使控件不被触摸的代码:

this.pwdform.controls.newpassword.markAsUntouched(); this.pwdform.controls.currentpassword.markAsUntouched(); this.pwdform.controls.confirmpassword.markAsUntouched();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-20
    • 1970-01-01
    相关资源
    最近更新 更多