【问题标题】:Reactive Form reset and forms validation反应式表单重置和表单验证
【发布时间】: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


【解决方案1】:

在模板中只需添加type=button

<button type="button" (click)="save()">Save</button>

在component.ts中

if (this.form1.invalid) {
    this.form1.markAllAsTouched();
} else {
    this.form1.reset();
}

Angular demo

【讨论】:

  • 如果我使用 ngSubmit 或按钮类型提交怎么办?
  • 模板中的#form="ngForm" (ngSubmit)="save(form)" 和保存中的save(form: NgForm) 和正文中的重置form.resetForm();
  • 删除这里的注释代码以检查stackblitz.com/edit/…
  • 感谢先生帮助我解决了我的问题,但请检查一下stackblitz.com/edit/…
  • user type="button" 因为你在调用 (click)="save" 所以输入 submit 没用 ..stackblitz.com/edit/…
猜你喜欢
  • 1970-01-01
  • 2018-07-08
  • 2017-12-30
  • 2019-05-04
  • 1970-01-01
  • 2020-12-05
  • 1970-01-01
相关资源
最近更新 更多