how to clear validation errors for Angular Material mat-error
This solution works with me. You need to do next:
formReset(form: FormGroup) {
form.reset();
Object.keys(form.controls).forEach(key => {
form.get(key).setErrors(null) ;
});
}
This reset the form and clear all error.
The form group has no "knowledge" about whether the actual HTML form has been submitted or not. It only keeps track of the form values/validity/enabled state. So resetting the form group does reset the values but not any state regarding whether the form has been submitted
.
To do this, you need to get a hold of the FormGroupDirective
and call resetForm()
on it.
Form Code Snippet
<form [formGroup]="addAttributeForm" fxLayout="column">
<!-- ... -->
</form>
In the component
@ViewChild(FormGroupDirective) formDirective: FormGroupDirective;
onSubmit(form: FormGroup) {
// do work
this.formDirective.resetForm();
}