How to reset validation error without resetting form in 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.
This finally worked for me:
this.form.reset();
Object.keys(this.form.controls).forEach(key => {
this.form.get(key).setErrors(null) ;
});
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.
With Angular Material, you need to define FormGroupDirective As well with FormGroup and FormControl
@ViewChild(FormGroupDirective) formGroupDirective: FormGroupDirective;
import { FormGroup, FormControl, FormGroupDirective } from '@angular/forms';
Reset FormGroupDirective in the onSubmit method with reactive form reset.
this.formGroupDirective.resetForm();
<br>
this.form.reset();
If the above FormGroupDirective reset does not work, try it with a timeout of 0 second
setTimeout(() => this.formGroupDirective.resetForm(), 0);
You could just iterate over each required field and call their setErrors method while passing null
onto them:
YOUR_FORM.controls.YOUR_FIELD_NAME.setErrors(null);
for instance when you have a username
and password
field:
this.loginForm.controls.username.setErrors(null);
this.loginForm.controls.password.setErrors(null);
Hope this helps!