Angular Material 表单验证在第一次提交后停止工作。提交后如何重置表单字段和验证器?

问题描述 投票:0回答:2

我的目标是重置表单字段和验证器。在第一次提交表单后,它目前正在清除两者。但是你可以在没有验证的情况下再次提交。 请查看我的 stackblitz - 正常提交表单,然后将表单字段留空并再次单击“添加”按钮。您会看到表单提交正常且没有错误。那不应该发生。每次单击“添加”按钮时,我都需要验证正常工作。我尝试了以下各种组合但无济于事:

  • .markAsPristine()
  • .markAsUntouched()
  • .clearValidators()
  • 使用表单组
  • 使用 formGroupDirective

HTML

<table style="width: 300px;">
    <thead>
        <tr>
            <th style="text-align: left;">Name</th>
            <th style="text-align: left;">Value</th>
            <th></th>
        </tr>
    </thead>
    <tbody>
        <tr *ngFor="let data of customData; let i=index;">
            <td>{{ data.name }}</td>
            <td>{{ data.value }}</td>
            <td style="text-align: right;"><button (click)="remove(i)">X</button></td>
        </tr>
    </tbody>
</table>

<br><br>

<form (ngSubmit)="add()">
    <mat-form-field class="full-width">
        <mat-label>Name</mat-label>
        <input matInput required [formControl]="customDataNameControl" />
        <mat-error *ngIf="customDataNameControl.hasError('required')">Required.</mat-error>
    </mat-form-field>
    <br><br>
    <mat-form-field class="full-width">
        <mat-label>Value</mat-label>
        <input matInput required [formControl]="customDataValueControl" />
        <mat-error *ngIf="customDataValueControl.hasError('required')">Required.</mat-error>
    </mat-form-field>
    <br><br>
    <button type="submit">Add</button>
</form>

TS

import { Component, OnInit } from '@angular/core';
import { FormControl, Validators } from '@angular/forms';

@Component({
  selector: 'app-item-list',
  templateUrl: './item-list.component.html'
})
export class ItemListComponent implements OnInit {
  customData = [
    { name: 'sample name 1', value: 'sample value 1' },
    { name: 'sample name 2', value: 'sample value 2' },
    { name: 'sample name 3', value: 'sample value 3' }
  ];
  customDataNameControl = new FormControl('', [Validators.required]);
  customDataValueControl = new FormControl('', [Validators.required]);

  constructor() {}

  ngOnInit(): void {}

  // Remove
  remove(index: any) {
    let confirmation = window.confirm('Delete? This cannot be undone!');
    if (confirmation == true) {
      this.customData.splice(index, 1);
    }
  }

  // Add
  add() {
    if (this.customDataNameControl.valid && this.customDataValueControl.valid) {
      let newCD: any = {
        name: this.customDataNameControl.value,
        value: this.customDataValueControl.value
      };
      this.customData.push(newCD);
      this.customDataNameControl.reset();
      this.customDataValueControl.reset();
      this.customDataNameControl.setErrors(null);
      this.customDataValueControl.setErrors(null);
    }
  }
}
angular validation angular-material angular-reactive-forms
2个回答
0
投票

可以使用

FormGroupDirective
resetForm()方法。 实例.


0
投票

我努力尝试根据示例重置表单但未成功,并引用了所有与此相关的旧 stackoverflow 问题。

在我的例子中,所有的 Material 表单都停止了工作,因为在我的应用程序的某个地方,在一个不相关的共享模块中,我处理了一条来自 RXJS 的异步消息,该消息触发了 Angular Zone 之外的导航。我发现一旦发生这种情况,这将破坏整个应用程序中 Angular Material 中的表单验证。因此,在引用解决此问题的解决方案时,我最接近的是:Navigation triggered outside Angular zone, did you forget to call 'ngZone.run()'?

在控制台中,我在控制台中有一个警告消息

Navigation triggered outside Angular zone, did you forget to call 'ngZone.run()'?

我知道要解决此消息,我必须在处理此异步消息时将导航包装在一个区域中。

this.zone.run(() => {
                    this.router.navigate(['/home']);
                });

一旦我正确处理了区域中的异步消息,我的 Angular Material Forms 就可以正常工作了。去图。

© www.soinside.com 2019 - 2024. All rights reserved.