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

Template

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

Component

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

Plunker

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

推荐答案

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

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

AFAIK,<mat-error>判断FormGroupDirective的有效性,而不是FormGroup,重置FormGroup不会重置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

Html相关问答推荐

Chrome中是否有一个本地显示密码功能,用于`input type = password/`?""<"">

自动字间距以适应行CSS

当表头包含特殊字符时,R Quarto发布的HTML表中不必要的大列宽

应用于文本而不是弹性容器的Flexbox属性

我能阻止浏览器跨跨区边界折叠空格吗?

标签数据的XPath?

Css网格:两列,除非小于150px

在Vue 3中使用v-Bind将计算(computed)属性传递给css url()

我的Django应用程序中出现模板语法错误

如何使用css横向显示英文和中日韩文字?

元素offsetTop在滚动容器中时没有更改

SVG的动态CSS

如何将多个类名组合到CSS中的一个关键帧

为什么我的网页显示网格区域彼此相邻,而不是我设置它们的方式?

无法在 CSS 中将 h1 标签居中

在锥形渐变进度条内创建空白的问题

Mediawiki css/html 信息框创建空白行

使用 css 将内容居中并向左对齐?

另一个 flex 元素之间的 CSS 空间

svg 内容超过元素