我遇到了这个问题,我有一个带有输入验证的表单,其中包含一个重置按钮,点击后应该重置表单,从而重置输入字段的状态以及提交的状态。输入字段被清除,但它们被标记为红色,因为一个验证标准是输入字段不得为空。有人可以解释为什么会发生这种情况或更好的解决方法。
提前致谢!
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();
}
}Run Code Online (Sandbox Code Playgroud)
<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 …Run Code Online (Sandbox Code Playgroud)