如何重置Angular Reactive Form

时间:2018-02-12 15:01:25

标签: angular angular-reactive-forms

我尝试过但未能找到重置角度形式的方法。

有人可以帮忙吗?

<form #thisIsAForm>
  <mat-form-field class="full-width">
    <input matInput placeholder="Weather">
  </mat-form-field>
</form>
<button mat-raised-button (click)="resetForm()">Reset</button>

export class Example{
  @ViewChild('thisIsAForm') thisIsAForm;

  resetForm() {
    this.thisIsAForm.reset();
  }
}

6 个答案:

答案 0 :(得分:16)

差不多!使用反应形式:

<form [formGroup]="myForm">
  <mat-form-field class="full-width">
    <input matInput placeholder="Weather" formControlName="weather">
  </mat-form-field>
</form>
<button mat-raised-button (click)="myForm.reset()">Reset</button>


export class Example{
  myForm: FormGroup;

  constructor(private fb: FormBuilder) { 
    this.myForm = fb.group({
      weather: ''
    });
  }

  // If the HTML code doesn't work, simply call this function
  reset() {
    this.myForm.reset();
  }
}

答案 1 :(得分:2)

<form [formGroup]="thisIsAForm" (ngSubmit)="onSubmit()">
  <mat-form-field class="full-width">
    <input formControlName="weather" placeholder="Weather">
  </mat-form-field>
</form>
<button mat-raised-button (click)="resetForm()">Reset</button>


export class Example{
  thisIsAForm: FormGroup;

  constructor() {
    this.thisIsAForm = new FormGroup(
      weather: new FormControl('')
    ); 
  }

  resetForm() {
    this.thisIsAForm.reset();
  }
}

答案 2 :(得分:0)

在这里,我重置了模板驱动的表单而不会弄脏表单。

    <form class="example-form" #charreplaceform="ngForm">
          <mat-form-field class="example-full-width">
            <input matInput #codepointSel="ngModel" (change)="createReplacementChar()" (keyup)="checkForNumber()"
              required [(ngModel)]="charReplaceInfo.codePoint" name="code-point" placeholder="Code Point (Only number)"
              [disabled]="isDisabled">
          </mat-form-field>

          <a (click)="refreshCharRecord(charreplaceform)">
            <i class="material-icons">
              loop
            </i>
          </a>
    </form>

    // in .ts
    refreshCharRecord(form: NgForm) { // getting the form reference from template 
    form.form.reset();   // here we are resetting the form without making form dirty
  }

答案 3 :(得分:0)

在Angular 8中,如果您这样做

<form #form="ngForm" (ngSubmit)="process(form)">

process(form: NgForm) { ...

使用--prod构建时会出现以下错误

  

“ FormGroupDirective”类型的参数不能分配给参数   类型为“ NgForm”。

(ngSubmit)

我所做的是将form模板引用注入为FormGroupDirective,然后调用resetForm()

<form #form (ngSubmit)="process(form)">

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

请参见FormGroupDirective

答案 4 :(得分:0)

我认为您需要在html代码中添加ngForm指令(如下所述)stackbliz示例,还需要在表单元素中添加名称和ngModel ngControl。

Stackbliz: Template Driven Form Reset

答案 5 :(得分:0)

对我来说,将type =“ reset”添加到“重置”按钮已解决问题

<button **type = "reset"** mat-raised-button (click)="resetForm()">Reset</button>