【发布时间】:2021-11-25 10:04:38
【问题描述】:
我知道这个问题以前被问过很多次。我想在提交后重置我的表单和验证。我使用 formGroup 创建一个表单。如果表单有效,我使用按钮提交表单我使用 form.reset() 重置表单它清除字段但不是错误我也尝试使用
this.form.markAsPristine();
this.form.markAsUntouched();
this.form.updateValueAndValidity();
重置表单验证但它不起作用
从下面给出的代码中,我可以重置表单,但输入字段仍然很脏或被触摸,结果输入字段标记为红色。有人可以建议我创建表单、重置表单和验证的最佳做法是什么。
我的html代码是
<mat-form-field class="example-full-width" appearance="outline" style="width: 100%;">
<input type="text" matInput formControlName="title" placeholder="Enter Module Title" #message maxlength="50">
<mat-error *ngIf="form.controls.title.hasError('required') && (form.controls.title.dirty || form.controls.title.touched)">
Module Title is <strong>required</strong>
</mat-error>
</mat-form-field>
<button (click)="save()"> Save</button>
这是我的 .TS 文件
@ViewChild('my2Form', { static: false }) my2Form!: NgForm;
this.form = this.fb.group({
title: ['',[Validators.required]],
});
save()
{ if(this.form.invalid)
{ this.form.markAllAsTouched();
return;
}
else
{
this.my2Form.resetForm();
this.form.markAsPristine();
this.form.markAsUntouched();
this.form.updateValueAndValidity();
this.form.markAsPristine();
}
【问题讨论】:
-
禁用保存按钮,直到 formGroup 无效,而不是
markAllasTouched -
我想告诉用户他/她错过了这些字段,所以我不能禁用按钮
-
我就是你需要的? stackblitz.com/edit/…
-
请使用角度材料 matinput 和 2-3 个字段,您将得到错误,即重置后输入字段标记为红色
-
如果你为你的问题创建stackblitz,我很容易帮助你
标签: angular forms angular-reactive-forms