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.
<form #form="ngForm" [formGroup]="checkForm" (ngSubmit)="submitForm(form)">
...
</form>
@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.
<mat-form-field>
<input matInput formControlName="name" placeholder="name" [errorStateMatcher]="errorMatcher" />
<mat-error *ngIf="checkForm.get('name').errors?.required">
Name is required.
</mat-error>
</mat-form-field>
// 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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…