I am using angular5 reactivemodule to show a form in my application. I had also used required validator which will subsequently make the field in red color and show an error
By default, Angular/Material watch formControl's error state not only by touched but also submitted status of the form, see below source code.
isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
return !!(control && control.invalid && (control.touched || (form && form.submitted)));
^^^^^^^^^^^^^^
}
For reason above, you also need to reset the form to unsubmitted status.
You can call resetForm of FormGroupDirective(getting instance by ViewChild) for it will reset both the form data and submit status.
@ViewChild('form') form;
submitForm() {
this.form.resetForm();
...
}
You can also overwrite the default one via implementing ErrorStateMatcher with custom conditions such as ignore submitted status of the form, and apply it on material components.
Name is required.
// define custom ErrorStateMatcher
export class CustomErrorStateMatcher implements ErrorStateMatcher {
isErrorState(control: FormControl, form: NgForm | FormGroupDirective | null) {
return control && control.invalid && control.touched;
}
}
// component code
@Component({...})
export class CustomComponent {
// create instance of custom ErrorStateMatcher
errorMatcher = new CustomErrorStateMatcher();
}
see fixed demo.