Reset Angular 7 Reactive From Validation

亡梦爱人 提交于 2020-04-16 05:48:50

问题


I am using an Angular Reactive form as a search form. I want to be able to reset the form. I did this with the following code:

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

The reset method does the following:

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

This makes all the form controls empty. But it does not reset the form validation. I deactivate the submit button if the form is not valid. This works when I first use the form. After I click on reset the validation does not work anymore. It seems to be deaktivated after submitting the form.

How can I solve this? What am I missing here?


回答1:


You can remove validations on specific formGroup/formcontrol by using clearValidators() for reactive forms.

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

After this, you have to update form control with the removed validator

this.formGroup.controls.controlName.updateValueAndValidity()

This helped me to resolve same issue, hope it helps you to




回答2:


Please use the following code:

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



回答3:


I am late to the party here the thing that worked for me was patch value. Which resets the validator control that was turning my inputs red.

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

Hope this help someone :)



来源:https://stackoverflow.com/questions/55915493/reset-angular-7-reactive-from-validation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!