我知道这个问题以前被问过很多次。我想在提交后重置我的表单和验证。我使用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();
}

发布于 2021-10-05 12:17:21
在模板中只需添加type=button:
<button type="button" (click)="save()">Save</button>在component.ts中
if (this.form1.invalid) {
this.form1.markAllAsTouched();
} else {
this.form1.reset();
}https://stackoverflow.com/questions/69445151
复制相似问题