Search code examples
angularformsresetangular12

How to reset form after submit using angular?


signup.component.html

<form (ngSubmit)="submitSignup()" #signupForm="ngForm">
  <div class="form-group">
    <label for="name">Name</label>
    <input type="text" class="form-control" id="name" name="name" [(ngModel)]="form.name" [ngModelOptions]="{standalone: true}" required>
    <small class="text-danger" [hidden]="!error.name">
      {{error.name}}
    </small>
  </div>

  <div class="form-group">
    <label for="email">Email address</label>
    <input type="email" class="form-control" id="email" name="email" [(ngModel)]="form.email" [ngModelOptions]="{standalone: true}" required>
    <small class="text-danger" [hidden]="!error.email">
      {{error.email}}
    </small>
  </div>

  <div class="form-group">
    <label for="password">Password</label>
    <input type="password" class="form-control" id="password" name="password" [(ngModel)]="form.password" [ngModelOptions]="{standalone: true}" required>
    <small class="text-danger" [hidden]="!error.password">
      {{error.password}}
    </small>
  </div>

  <button type="submit" class="btn btn-primary" [disabled]="!form.name || !form.email || !form.password">Submit</button>
</form>

signup.component.ts

import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-signup',
  templateUrl: './signup.component.html',
  styleUrls: ['./signup.component.css']
})
export class SignupComponent implements OnInit {

  public form = {
    name: null,
    email: null,
    password: null
  }
  public url = "http://localhost/ang/projectAPI/api/";

  constructor(private http:HttpClient) { }

  public error:any = [];
  public success = null;

  ngOnInit(): void {
  }

  submitSignup() {
    this.http.post(this.url+"signup",this.form).subscribe(
      data=>this.handleResponse(data),
      error=>this.handleError(error)
    );
    this.form.reset();
  }
  handleResponse(data:any){
    this.success = data.message;
  }
  handleError(error:any){
    this.error = error.error.errors;
  }
}

I am new in angular and in the above code I am trying to reset my form after submit but when I click on submit form reset function not working. I have tried to solve issue with form.reset(); and this.form.reset(); function in angular but it throw an error i.e. Property 'reset' does not exist on type '{ name: any; email: any; password: any; confirm_password: any; }'. I don't know why this happening? Please help me.

Thank You


Solution

  • After submitting the form set the form value to null.

    submitSignup() {
        this.http.post(this.url+"signup",this.form).subscribe(
          data=>this.handleResponse(data),
          error=>this.handleError(error)
        );
        //set all value to null
        this.form = {
          name: null,
          email: null,
         password: null
        };
      }