1

我有一个角度形式,我想将所有输入字段标记为原始并在提交一次后禁用提交按钮。只是当这个页面第一次加载时。

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

2 回答 2

1

你可以使用formGroup.markAsPristine()

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

并在您的模板中

<!-- ... -->

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

<!-- ... -->
于 2020-05-15T17:21:33.457 回答
1

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

1-您需要获取 FormGroupDirective

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

2-重置表单和验证消失

  onSubmit() {
    if (this.form.valid) {
      // Remove the state of validation
      this.formDirective.resetForm(); 
    }
  }
于 2020-05-15T17:53:51.773 回答