I'm trying to reset a form after I've added a value.
Form Code Snippet
<form [formGroup]="addAttributeForm" fxLayout="column">
<mat-form-field>
<input matInput formControlName="title" placeholder="Title" required>
<mat-error>This field is required</mat-error>
</mat-form-field>
</form>
In the component
onSubmit(form: FormGroup) {
// do work
form.reset();
}
What I'm observing:
form.markAsPristine()
, form.markAsUntouched()
and combining all three.How can I reset the form so the mat-error is not displayed?
To fix the error, add MatInputModule and MatFormFieldModule inside a necessary module or app.
Error messages can be shown under the form field underline by adding mat-error elements inside the form field. Errors are hidden initially and will be displayed on invalid form fields after the user has interacted with the element or the parent form has been submitted.
The <mat-form-field> is a component that is used to wrap multiple MAT components and implement common text field styles of the form-field such as hint message, underlines, and floating label. These five MAT components are designed to work inside the form-field: <mat-chip-list> <input matNativeControl>
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With