重置 Angular 7 反应来自验证

Reset Angular 7 Reactive From Validation

我正在使用 Angular 响应式表单作为搜索表单。我希望能够重置表格。我用以下代码做到了这一点:

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

重置方法执行以下操作:

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

这会使所有表单控件都为空。但它不会重置表单验证。如果表单无效,我会停用提交按钮。这在我第一次使用表单时有效。单击重置后,验证不再起作用。提交表单后好像被取消激活了。

我该如何解决这个问题?我在这里错过了什么?

请使用以下代码:

this.myForm.reset()
Object.keys(this.myForm.controls).forEach(key => {
  this.myForm.controls[key].setErrors(null)
});

您可以使用 clearValidators() 删除特定 formGroup/formcontrol 的验证 对于反应形式。

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

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

this.formGroup.controls.controlName.updateValueAndValidity()

这帮助我解决了同样的问题,希望对您有所帮助

我来晚了,对我有用的是补丁值。它重置了将我的输入变为红色的验证器控件。

this.formgroup.patchValue({ formControlName: [null, Validators.required] });

希望这对某人有所帮助:)

我遇到了想要即时更改表单验证类型的问题。像下面这样的组合对我来说效果很好,我在应用程序视图中摆脱了各种问题:

onChange(event: any) {
   this.valForm.controls.controlName.setErrors(null);
   this.valForm.controls.controlName.clearValidators();
   if (conditionA) {
       this.valForm.get('controlName').setValidators([Validators.required, this.patternA]);
       this.valForm.controls.controlName.updateValueAndValidity();
   } else {
       this.valForm.get('controlName').setValidators([Validators.required, this.patternB]);
       this.valForm.controls.controlName.updateValueAndValidity();
   }
}

我希望它对你和我一样有用!