Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reset validation error without resetting form in angular?

Tags:

forms

angular

I have an angular template driven form. and I want to reset all the validation error and make it as untouched without resetting the form. How to do that in angular? I have tried the following method

onAdd(form: NgForm) {

form.form.markAsPristine();
form.form.markAsUntouched();

}

but this doesn't work.

link:- https://stackblitz.com/edit/angular-ezixd4

current behavior:- when I click to submit an empty form, all the field is marked with error and when I click add it adds the field but the above function doesn't remove the error message.

expected behavior:- when I click to submit an empty form, all the field is marked with error and when I click add it adds the field and it should remove the error message on the form (or in the added files).

In this form, I am adding input field with add Button and I want to clear any error message before the user has the chance to interact with the form.

like image 956
rahul Kushwaha Avatar asked Apr 20 '19 19:04

rahul Kushwaha


2 Answers

This finally worked for me:

this.form.reset();
Object.keys(this.form.controls).forEach(key => {
    this.form.get(key).setErrors(null) ;
});
like image 181
gal007 Avatar answered Sep 26 '22 13:09

gal007


the class mat-input-invalid depends partly on the submitted state of the form. So when you submit the form, the submitted property is switched to true. markAsPristine() or markAsUntouched() does not reset the submitted flag, thus the errors still show. I see two possibilities. One quick and dirty, which when I tested seems to work in your case. I cannot promise that it will in all cases, but you can experiment around with it and see if it will work. That is, you call resetForm() which does reset the submitted property. But yes, you want to keep the values that are set.. so, we pass the value of the current state of the form in the reset:

onAdd(form: NgForm) {
  this.specification.push(++this.num);
  form.resetForm(form.value);  
}

DEMO

So that was the dirty way, a more controlled way would be to use the ErrorStateMatcher, that is also mentioned in the docs. With that you can choose when to show the error messages.

like image 21
AT82 Avatar answered Sep 22 '22 13:09

AT82