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

新手上路,请多包涵

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

模板

<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/

原文由 efarley 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 691
2 个回答

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

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

AFAIK, <mat-error> check the validity of FormGroupDirective , not FormGroup , and FormGroup does not reset FormGroupDirective .这有点不方便,但要清除 <mat-error> 您还需要重置 FormGroupDirective

为此,在您的模板中,定义一个变量,如下所示:

 <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 发布,翻译遵循 CC BY-SA 3.0 许可协议

除了 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();
  }
}

原文由 Maximillion Bartango 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题