How can I reset Angular Reactive Form

34,439

Solution 1

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

Solution 2

I think you need to add ngForm directive in the html code as mentioned below stackbliz example also add name and ngModel ngControl to form elements.

Stackbliz: Template Driven Form Reset

Solution 3

In Angular 8, if you do

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

process(form: NgForm) { ...

You'll get the following error when you build with --prod

Argument of type 'FormGroupDirective' is not assignable to parameter of type 'NgForm'.

on (ngSubmit)

What I did was to inject form template reference as FormGroupDirective then call resetForm().

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

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

See FormGroupDirective

Share:
34,439
physicsboy
Author by

physicsboy

Updated on July 09, 2022

Comments

  • physicsboy
    physicsboy almost 2 years

    I have tried and failed to find the way in which to reset my angular form.

    Can somebody help?

    <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();
      }
    }
    
  • axl-code
    axl-code about 6 years
    Arg @trichetriche was faster :P