I got this problem where I have a form with input validation that contains a reset button which upon clicking should reset the form and thus the state of the inputfields as well as the submitted state. The inputfields are cleared, however they are marked red since one validation criterion is that the inputfield shall not be empty. Can someone explain why this happens or better how to fix it.
Thanks in advance!
import { Component, OnInit } from "@angular/core";
import { NgForm } from "@angular/forms";
@Component({
selector: "app-contact",
templateUrl: "./contact.component.html",
styleUrls: ["./contact.component.css"],
})
export class ContactComponent implements OnInit {
constructor() {}
ngOnInit(): void {}
sendMessage(form: NgForm): void {
if (form.invalid) {
return;
}
form.resetForm();
form.reset();
}
clear(form: NgForm): void {
form.resetForm();
}
}
<mat-card>
<form
class="contactForm"
(ngSubmit)="sendMessage(postForm)"
#postForm="ngForm"
[ngFormOptions]="{ updateOn: 'submit' }"
>
<mat-form-field class="nameField">
<mat-label> Your Name </mat-label>
<input
matInput
type="text"
required
name="inputName"
ngModel
#name="ngModel"
/>
<mat-error *ngIf="true">
Please enter a name
</mat-error>
</mat-form-field>
<mat-form-field class="emailField">
<mat-label> Your E-Mail </mat-label>
<input
matInput
type="email"
required
name="inputEmail"
ngModel
email
#email="ngModel"
/>
<mat-error *ngIf="true">
Please enter a valid email address
</mat-error>
</mat-form-field>
<mat-form-field class="msgField">
<mat-label> Your Message </mat-label>
<textarea
matInput
type="text"
required
name="message"
ngModel
#message="ngModel"
>
</textarea>
<mat-error *ngIf="true">
Please enter a message
</mat-error>
</mat-form-field>
<button mat-raised-button class="sendBtn" color="accent" type="submit">
Send
</button>
<button
mat-raised-button
class="clearBtn"
color="warn"
(click)="clear(postForm)"
>
Clear
</button>
</form>
</mat-card>