【发布时间】:2020-08-04 08:18:15
【问题描述】:
我遇到了这个问题,我有一个带有输入验证的表单,其中包含一个重置按钮,单击该按钮应重置表单,从而重置输入字段的状态以及提交的状态。输入字段被清除,但它们被标记为红色,因为一个验证标准是输入字段不得为空。有人可以解释为什么会发生这种情况或更好地解决它。
提前致谢!
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>
【问题讨论】:
标签: angular forms validation input frontend