【问题标题】:angular reset reactive form角复位反应形式
【发布时间】:2020-05-20 02:45:56
【问题描述】:

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

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();

    }
  }

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

【问题讨论】:

  • 似乎是问题的重复:stackoverflow.com/questions/34608361/…
  • @Ivilin Stouanov,了解如何使用 resetFormtype=reset
  • reset 将通过标记所有后代标记为原始和未触及,并将所有后代的值重置为 null 来重置 FormGroup。 ??????????

标签: angular angular-reactive-forms reset reactive-forms


【解决方案1】:

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

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

Stackblitz Example

【讨论】:

  • 这将重置 from 但他在单击保存后尝试重置并从组件主体运行 insertNote 方法
【解决方案2】:

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

【讨论】:

    【解决方案3】:

    你可以像(click)="noteForm.reset()"这样使用formGroup 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 ?

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

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

    demo ?

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

    【讨论】:

      【解决方案4】:
      for (let control in this.form.controls) {
        this.form.controls[control].setErrors(null);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-06-04
        • 2021-07-24
        • 1970-01-01
        • 1970-01-01
        • 2018-07-30
        • 2020-04-03
        相关资源
        最近更新 更多