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

时间:2021-06-22 00:49:19

标签: angular validation angular-material angular-reactive-forms

我的目标是重置表单域和验证器。在第一次提交表单后,它目前正在清除两者。但是随后您无需验证即可再次提交。 Please see my 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);
    }
  }
}

1 个答案:

答案 0 :(得分:0)

您可以使用 FormGroupDirective resetForm() 方法。 Live example