重置Angular 7反应表单验证

问题描述 投票:0回答:2

我使用Angular Reactive表单作为搜索表单。我希望能够重置表单。我用以下代码完成了这个:

<button type="reset" (click)="onReset()">
    Reset
</button>

reset方法执行以下操作:

onReset(){
    this.myForm.reset();
    this.myForm.markAsPristine();
    this.myForm.markAsUntouched();
}

这使得所有表单控件都为空。但它不会重置表单验证。如果表单无效,我将停用提交按钮。这在我第一次使用表单时有效。点击重置后,验证不再有效。提交表格后,它似乎已经失效了。

我怎么解决这个问题?我在这里错过了什么?

angular validation reset
2个回答
2
投票

您可以通过对活动表单使用clearValidators()来删除特定formGroup / formcontrol上的验证。

 this.formGroup.clearValidators() or      
 this.formGroup.controls.controlName.clearValidators()

在此之后,您必须使用已删除的验证程序更新表单控件

this.formGroup.controls.controlName.updateValueAndValidity()

这有助于我解决同样的问题,希望它可以帮到你


0
投票

请使用以下代码:

this.myForm.reset()
Object.keys(this.myForm.controls).forEach(key => {
  this.myForm.controls[key].setErrors(null)
});
© www.soinside.com 2019 - 2024. All rights reserved.