繁体   English   中英

角度复位反应形式

[英]angular reset reactive form

我正在尝试在发送表单后重置我的表单,但只有该值设置为 null。

组件.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>

组件.ts

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

      this.noteForm.reset();

    }
  }

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

在此处输入图片说明

尝试使用 button type="reset"选项

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

Stackblitz 示例

您可以使用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 文件中相应地替换名称。

您可以像这样使用 formGroup重置方法(click)="noteForm.reset()"并且此方法会将所有后代标记为原始未触及,并将所有后代的值标记为 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>

演示🚀

使用有角度的材料,您无需检查控件是否被触摸

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

演示🚀

我不使用这个<button type="reset">Reset</button>因为大多数时候我想从组件重置表单,有时我想在重置后传递初始值

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM