angular 重置反应形式

angular reset reactive form

发送表单后我试图重置表单,但只有值设置为空。

component.html

  <div *ngIf="!loading" fxLayout="row" class="note-textarea">
    <form  fxFlex fxLayout="column" fxLayoutGap="10px" [formGroup]="noteForm">
      <mat-form-field fxFlex>
        <textarea matInput #note rows="1" maxlength="100" placeholder="Note" formControlName="description"></textarea>
        <mat-hint align="end">{{note.value?.length || 0}}/100</mat-hint>
        <mat-error *ngIf="noteForm.get('description').errors && noteForm.get('description').touched">description is required</mat-error>
      </mat-form-field>
      <div fxFlex>
        <button mat-stroked-button class="save-btn" (click)="insertNote()">Save</button>
      </div>
    </form>
  </div>

component.ts

  noteForm: FormGroup = this.formBuilder.group({
    description: new FormControl(null, Validators.required)
  })
 insertNote() {
   // bunch of code 

      this.noteForm.reset();

    }
  }

问题是输入字段被标记为脏,如下所示:

您可以使用 ngForm 这样做

In your Html file

<form  fxFlex fxLayout="column" fxLayoutGap="10px" [formGroup]="noteForm" #noteForm="ngForm">

In your ts file

 @ViewChild('noteForm', { static: true }) noteForm: NgForm;
//to reset form
this.noteForm.resetForm();

相应地替换 HTML 和 TS 文件中的名称。

尝试使用按钮 type="reset" 选项

<button type="reset">Reset</button> 

Stackblitz Example

您可以像这样使用 formGroup reset 方法 (click)="noteForm.reset()" 并且此方法将标记所有后代都标记为 pristineuntouched,所有后代的值为null。

例子

<div [formGroup]="form">
    <input placeholder="description..." type="text" formControlName="description" ><br/><br/>

    <div
        *ngIf="form.get('description').hasError('required') && (form.get('description').dirty || form.get('description').touched) ">

        description is required

    </div>
    <button type="button" (click)="insertNote()">Add </button> &nbsp;
    <button type="button" (click)="form.reset()">reset </button>

</div>

demo

使用 angular material 你不需要检查控件是否被触摸

   <mat-error *ngIf="noteForm.get('description').hasError('required')">
       description is required
   </mat-error>

demo

I don't use this <button type="reset">Reset</button> because most the time I want to reset the form from the component and sometimes I want to pass initial value after reset

for (let control in this.form.controls) {
  this.form.controls[control].setErrors(null);
}