【问题标题】:What is the most effective way to approach resetting a reactive angular form?重置反应角度形式的最有效方法是什么?
【发布时间】:2018-02-11 01:34:18
【问题描述】:

我有 Reactive Form 使用 Angular Material 输入 (mdInput),它使用 FormBuilder 以下列方式初始化:

contactForm: FormGroup;

this.contactForm = this.fb.group({
  name: ['', [Validators.required, Validators.maxLength(128)]],
  email: ['', [Validators.required, Validators.email]],
  subject: ['', [Validators.required, Validators.maxLength(128)]],
  message: ['', [Validators.required, Validators.maxLength(1000)]]
});

onSubmit(): void {
  this.resetForm();
}

private resetForm(): void {
  this.contactForm.reset();
}    

使用与各个 FormControl 元素相关联的 Angular Material 输入,并与 (ngSubmit) 挂钩:

<form [formGroup]="contactForm" (ngSubmit)="onSubmit()">
  <md-input-container>
    <input mdInput formControlName="name" placeholder="Name">
  </md-input-container>

  <button type="submit" md-raised-button [disabled]="contactForm.invalid">Submit</button>

FormGroupcontactForm 上调用reset() 时(this.contactForm.reset(), the form elements values are successfully cleared/replaced with empty strings, but the elements are both immediately dirty and touched with CSS classesng-invalid&amp;&amp;ng-touchedpresent on the elements. Strangely they also have theng-pristineCSS class on them after thereset()`。

重置表单的最有效方法是什么,包括清除/重置FormControl 值并将它们标记为未触摸且未脏?是使用markAsUntouched() 还是markAsPristine()?是使用带有特定选项的setValue()reset() 吗?目标是重置表单,就像用户第一次与之交互一样。

更新:这是一个Stackblitz,显示了这个问题的实际效果。

感谢您提供的任何帮助。

【问题讨论】:

  • 不应该这样。根据源代码,reset 会将表单标记为未触及和原始。见github.com/angular/angular/blob/master/packages/forms/src/…
  • 我已更新答案以包含 Stackblitz 以演示实际问题。您会注意到 onSubmit 调用了 reset(),导致所有具有 Validators 的输入都被触摸并变脏。谢谢!
  • 不知何故使用ngSubmit 会破坏流程。我可以看到所有输入未触及+原始,但错误仍然存​​在。如果您将提交按钮更改为 &lt;button type="button" (click)="onSubmit()" 之类的东西,它将起作用

标签: angular angular-material2 angular-reactive-forms


【解决方案1】:

正如@Harry Ninh 在 cmets 中所提到的,使用常规按钮而不是 ngSubmit 将修复该行为。这是因为默认情况下,当输入为invalidtouchedsubmitted 时,会显示材料错误。关于它here 有一个很长的线索,但基本上,在表单控件或表单组上调用reset() 不会重置实际表单,只是重置值。

您可以执行以下操作之一:

  1. 使用@Harry Ninh 提到的解决方法
  2. 使用ViewChild 访问FormGroupDirective 并将其重置。

看这里:

@ViewChild(FormGroupDirective) myForm;

contactForm: FormGroup;

constructor(private fb: FormBuilder) {
  this.createForm();
}

private createForm(): void {
  this.contactForm = this.fb.group({
    name: ['', [Validators.required, Validators.maxLength(128)]],
    email: ['', [Validators.required, Validators.email]],
    subject: ['', [Validators.required, Validators.maxLength(128)]],
    message: ['', [Validators.required, Validators.maxLength(1000)]]
  });
}

onSubmit(): void {
  this.resetForm();
}

private resetForm(): void {
  if (this.myForm) {
    this.myForm.resetForm();
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-12
    • 2018-11-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多