将 formGroupDirective 用于重置表单 - Angular 反应式表单

Usage of formGroupDirective for reset form - Angular reactive form

我正在尝试找到重置 angular 反应形式的最佳方法。我对重置反应形式有点困惑,无法找到哪种方法适用于模板驱动形式,哪种方法是反应形式。 现在我已经使用 'formGroupDirective' 进行重置,但出现如下所示的控制台错误。

这就是我使用 formGroupDirective 进行重置的方式。

模板文件:

<form 
  ...
  #formDirective="formGroupDirective" 
>

TS 文件:

import { ViewChild, ... } from '@angular/core';
import { FormGroupDirective, ... } from '@angular/forms';

export class MyComponent {
 ...
 @ViewChild('formGroupDirective') private formGroupDirective: FormGroupDirective;

  constructor(... )

  private someFunction(): void { 
    ...
    formGroupDirective.resetForm();
  }
}

这里有一件事我没看明白,FormGroupDirective和FormDirective有什么区别。哪个更适合反应形式。 甚至我们可以通过

之类的 formGroup 名称进行重置
this.formGroup.reset();

所以如果我们能够通过 formGroup 名称重新设置,那么为什么我们需要使用指令。如果有人有想法,请帮助我理解这些差异。

如果您正在做响应式表单,您应该已经为组件中的表单定义了一个 FormGroup。对此使用重置。在这种情况下没有理由使用模板引用变量。

这是我的一个:

  ngOnInit(): void {
    this.productForm = this.fb.group({
      productName: ['', [Validators.required,
                         Validators.minLength(3),
                         Validators.maxLength(50)]],
      productCode: ['', Validators.required],
      tags: this.fb.array([]),
      description: ''
    });
  }

  displayProduct(product: Product): void {
    if (this.productForm) {
      this.productForm.reset();
    }
    // ...
  }

我在属性productForm中定义了表单组,然后使用that属性调用reset

我的 displayProduct 方法在每次用户选择不同的产品进行编辑时被调用。它会重置表单并使用所选产品的数据重新填充它。

此语法:

#formDirective="formGroupDirective" 

是一个模板引用变量,由井号 (#) 指示。这通常用于模板驱动的表单中以访问表单组,因为表单组是 not 在代码中定义的(因为它是反应式表单)。

响应式表单中的FormGroupDirective将HTML中的表单元素绑定到组件代码中定义的表单组。

我的看起来像这样:

<form novalidate
      (ngSubmit)="saveProduct()"
      [formGroup]="productForm">

注意 [formGroup] <-- FormGroupDirective

设置为productForm,也就是组件代码中定义的我的FormGroup属性的名称:

this.productForm = ...

如果您使用的是 Reactive Forms,您可以简单地使用 FormGroup 上的 reset() 方法来清除所有表单值并再次将控件标记为原始,正如已经指出的那样。但是您也可以使用 FormGroupDirective 来使用 resetForm(),因为这会将提交的表单 属性 标记为 false,而常规的 reset() 方法不会这样做。

如果您使用 Angular Material,这将特别有用,因为默认的 ErrorStateMatcher 将检查表单是否已提交作为显示表单错误消息的条件之一。你可以这样使用它:

@ViewChild(FormGroupDirective) formRef: FormGroupDirective;

然后:

this.formRef.resetForm();

无需向您的 HTML 添加任何内容。

更多信息:https://github.com/angular/angular/pull/10715