提问者:小点点

Angular 5 FormGroup重置不会重置验证器


我的页面上有一个表单,当我调用FormGroup. reset()时,它会将表单类设置为ng-pristine ng-untouch,但FormControl.hasError(…)仍然返回truthy。我在这里做错了什么?

模板

<form [formGroup]="myForm" (ngSubmit)="submitForm(myForm)">
  <mat-form-field>
    <input matInput formControlName="email" />
    <mat-error *ngIf="email.hasError('required')">
      Email is a required feild
    </mat-error>
  </mat-form-field>
  <mat-form-field>
    <input matInput type="password" formControlName="password" />
    <mat-error *ngIf="password.hasError('required')">
      Password is a required feild
    </mat-error>
  </mat-form-field>
  <button type="submit">Login</button>
</form>

组件

export class MyComponent {
  private myForm: FormGroup;
  private email: FormControl = new FormContorl('', Validators.required);
  private password: FormControl = new FormControl('', Validators.required);

  constructor(
    private formBuilder: FormBuilder
  ) {
    this.myForm = formBuilder.group({
      email: this.email,
      password: this.password
    });
  }

  private submitForm(formData: any): void {
    this.myForm.reset();
  }
}

普朗克

https://embed.plnkr.co/Hlivn4/


共3个答案

匿名用户

它(FormGroup)行为正确。您的表单需要用户名和密码,因此当您重置表单时,它应该无效(即没有用户名/密码的表单无效)。

如果我理解正确,您的问题是为什么红色错误在您第一次加载页面时不存在(表单也无效),但在您单击按钮时弹出。当您使用材料时,这个问题尤其突出。

AFAIK,

为此,在您的模板中,定义一个这样的变量:

<form [formGroup]="myForm" #formDirective="ngForm" 
  (ngSubmit)="submitForm(myForm, formDirective)">

在您的组件类中,调用formDirective. resetForm()

private submitForm(formData: any, formDirective: FormGroupDirective): void {
    formDirective.resetForm();
    this.myForm.reset();
}

GitHub问题:https://github.com/angular/material2/issues/4190

匿名用户

除了Harry Ninh的解决方案之外,如果您想访问组件中的formDirective而无需选择表单按钮,那么:

模板:

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

组件:

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

export class MyComponent {
 ...
 @ViewChild('formDirective') private formDirective: NgForm;

  constructor(... )

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

匿名用户

阅读评论后,这是正确的方法

// you can put this method in a module and reuse it as needed
resetForm(form: FormGroup) {

    form.reset();

    Object.keys(form.controls).forEach(key => {
      form.get(key).setErrors(null) ;
    });
}

没有必要调用form. clearValidators()