反应式表单重置和表单验证

Abh*_*wal 1 forms angular angular-reactive-forms

我知道这个问题以前被问过很多次。我想在提交后重置我的表单和验证。我使用 formGroup 创建一个表单。如果表单有效,我使用了一个按钮来提交表单,我使用 form.reset() 重置了表单,它清除了字段,但没有清除我也尝试使用的错误

this.form.markAsPristine();
this.form.markAsUntouched();
this.form.updateValueAndValidity();
Run Code Online (Sandbox Code Playgroud)

重置表单验证但它不起作用

从下面给出的代码中,我可以重置表单,但输入字段仍然脏或被触摸,结果输入字段标记为红色。有人可以建议我创建表单、重置表单和验证的最佳实践是什么。

我的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>
Run Code Online (Sandbox Code Playgroud)

这是我的 .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();
        }
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

nav*_*ath 6

在模板中只需添加type=button

<button type="button" (click)="save()">Save</button>
Run Code Online (Sandbox Code Playgroud)

在组件.ts中

if (this.form1.invalid) {
    this.form1.markAllAsTouched();
} else {
    this.form1.reset();
}
Run Code Online (Sandbox Code Playgroud)

角度演示