提交一次后使所有输入字段保持原始状态

Make all input field pristine after submitting once

我有一个 angular 表单,我想将所有输入字段标记为原始状态,并在提交一次后禁用提交按钮。就在第一次加载此页面时。

<form class="example-form" [formGroup] = "form" (ngSubmit) = "onSubmit()">
            <div class="inputs">
                 <h3>Create Product</h3>
                <div>
                    <mat-form-field class="example-full-width">
                        <mat-label>Product Name*</mat-label>
                        <input matInput 
                           formControlName = "productName"
                        >
                      </mat-form-field>
                       <br>
                      <div class="errorField" *ngIf = "form.get('productName').touched && 
                       form.get('productName').errors?.required" > Product name is required</div>
                </div>

                <mat-checkbox value = "checked" (change)="addAnother(checked)">Add Another</mat-checkbox>
                <br><br>
                <div class="buttons">
                    <button type="button" routerLink = "/products" class="back" mat-raised- 
                          button>Back</button>
                    <button
                      [disabled] = "!form.valid"
                    mat-raised-button>Save</button>
                </div>
            </div> 
      </form>

您可以使用 formGroup.markAsPristine():

onSubmit () {
 this.formGroup.markAsPristine();
 this.hasSubmitted = true;
}

并在您的模板中

<!-- ... -->

<button
  [disabled] = "!form.valid || hasSubmitted"
  mat-raised-button>
  Save
</button>

<!-- ... -->

我想你可以重置表单并删除验证状态

1- 您需要获取 FormGroupDirective

 @ViewChild(FormGroupDirective, { static: false }) formDirective: FormGroupDirective;

2- 重置表单,验证消失

  onSubmit() {
    if (this.form.valid) {
      // Remove the state of validation
      this.formDirective.resetForm(); 
    }
  }