Reputation: 439
I try to get the form to be clear without the validation error messages after calling reset()
.
my form looks clean on load, and that is expected:
however, if the user pressed the register button, and there was an error, I trigger the
form.reset()
method. I expect the form to look like the above picture, since the touch, pristine, dirty props are all as when the form is initially loaded.
but instead, it clears the values, but shows me the validation error.
Can anyone help me please get it to the initial state, a clear form without the validation errors shows up?
This is a reactive form. let me know if you need more information. Thanks!
Upvotes: 10
Views: 6445
Reputation: 1914
Global ErrorStateMatcher
With this method you won't have to reset the Form for each component. It goes throughout your application.
1- Create a file and name it something like default-error-state.matcher.ts
with this code in it:
import { FormControl, FormGroupDirective, NgForm } from '@angular/forms';
import { ErrorStateMatcher } from '@angular/material/core';
export class DefaultErrorStateMatcher implements ErrorStateMatcher {
isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
return !!(control && control.invalid && (control.dirty || control.touched));
}
}
2- In app.module.ts
provide it in the provider section
// import the files
import { ErrorStateMatcher } from '@angular/material/core';
import { DefaultErrorStateMatcher } from './default-error-state.matcher';
Then
providers: [
{ provide: ErrorStateMatcher, useClass: DefaultErrorStateMatcher }
],
DONE
Upvotes: 0
Reputation: 57
You can use method .markAsPristine()
of your form to reset validation:
this.RegForm.reset();
this.RegForm.markAsPristine();
Upvotes: 0
Reputation: 11
static resetForm(formGroup: FormGroup) {
let control: AbstractControl = null;
formGroup.reset();
formGroup.markAsUntouched();
Object.keys(formGroup.controls).forEach((name) => {
control = formGroup.controls[name];
control.setErrors(null);
});
}
Upvotes: 1
Reputation: 513
It looks like you are using Angular Materials. If so ,you must reset FormGroupDirective too,only resetting the FormGroup is not enough.
private registerForm(fData: any,formDirective: FormGroupDirective): void {
formDirective.resetForm();
this.RegForm.reset();
}
<form [formGroup]="RegForm" #formDirective="ngForm"
(ngSubmit)="registerForm(RegForm,formDirective)">
Upvotes: 23
Reputation: 1
Are you using something like this?
// Reactive Form
constructor(private _builder:FormBuilder) {
this.createForm();
}
createForm() {
this.form = this._builder.group({
key: this.value,
});
}
// Option 1
resetForm() {
this.form.reset();
}
// Option 2 - create form again
resetForm() {
this.createForm()
}
// Template Form
---- HTML ----
<form #myForm="ngForm"></form>
---- TS ----
@ViewChild('myForm') myForm;
resetForm() {
if (this.myForm) {
this.myForm.reset();
}
}
Upvotes: 0