16 Apr 2017

Clearing Forms in Angular v6

I was recently working on an Angular (aka Angular2 aka Angular4 aka Angular 6) application where a user triggers a modal, completes a form within the modal, and submits. Unfortunately, the form wasn’t clearing after a form submission and manually resetting every ngModel seemed extremely tedious. Thankfully the solution to this problem is easy and takes just two lines of real code to get the job done.

First, we’ll start with a basic component.

// src/app.component.ts

import { Component } from '@angular/core';
import { DummyService } from './dummy.service';

@Component({
  selector: 'app-root',
  template: `
    <form #myForm="ngForm" (ngSubmit)="submitForm(myForm.value)">
      <label for="name">Name: </label>
      <input placeholder="Name"
        type="text"
        id="name"
        name="name"
        [(ngModel)]="name">

      <label for="name">Title: </label>
      <input placeholder="Title"
        type="text"
        id="title"
        name="title"
        [(ngModel)]="title">

      <button type="submit">Submit</button>
    </form>
    <span *ngIf="submittedUser">{{submittedUser}}</span>
  `
})
export class AppComponent {
  submittedUser: string;
  name: string;
  title: string;

  constructor(private dummyService: DummyService) { }

  submitForm(form) {
    this.dummyService.create(form).subscribe((res) => {
      this.submittedUser = res.message;
    });
  }

}

In this component we’ve provided a form template with two inputs: name and title. Within the component class we’ve defined a private dummyService which we’ll use as a mock service to “POST” our form. When the user clicks “Submit”, submitForm will call this.dummyService.create() and we set the response to the submittedUser property which conditionally displays in our view through <span *ngIf="submittedUser">.

Complete the form below, click “Submit”, and you should see the conditional <span> display our response but the form inputs are still populated.

To fix this, we’ll need to leverage Angular’s ViewChild decorator. ViewChild allows us to query our view to get an element or directive of our choice. In this case, we want a ViewChild for our form.

To do this, we’ll need to import ViewChild (Thanks to Chris Sevilleja for introducing me to ViewChild).

// src/app.component.ts

import { Component, ViewChild } from '@angular/core';

Then in our component class, we can set a ViewChild property to our form’s template variable myForm which we declared earlier: <form #myForm="ngForm" (ngSubmit)="submitForm(myForm.value)">.

// src/app.component.ts

export class AppComponent {
  @ViewChild('myForm') formValues; // Added this
  submittedUser: string;
  name: string;
  title: string;

  constructor(private dummyService: DummyService) { }

  ...

}

Now we can add the one line to clear our form on a successful response.

// src/app.component.ts

...

submitForm(form) {
  this.dummyService.create(form).subscribe((res) => {
    this.submittedUser = res.message;
    this.formValues.resetForm(); // Added this
  });
}

Try it again below and experience the magic of resetForm().


Before you go...

Feeling stuck copying and pasting from tutorials that don't build realistic applications?

Become an Angular developer by building a real application using open-source libraries with a real API and database.

"The advice and techniques in this book landed me my dream job and literally doubled my salary. Well worth the $99 bucks, so much so that I have been waiting for it to be for sale just to pay the man for the good he has done to my career." -Levi Robertson

CLICK HERE FOR A FREE 8 CHAPTER PREVIEW OF THE ANGULAR TUTORIAL

Learning a front-end framework is hard. "Getting started" tutorials cover the basics but you leave thinking, "Okay, now how do I build something with this?"

The truth is, getting started tutorials aren't all that great for beginners. They're demos to highlight as many features as quickly as possible.

They're great for showing off what a framework can do. They aren't so great for teaching you how to build web apps.

The end result is a basic application that doesn't mimick what it's like building real applications as a front-end developer.

You'll work with a mocked API and database. Application architecture isn't covered. Automated testing is skipped altogether.

Trust me, I've been there. But those days are over.

With The Angular Tutorial, you'll learn how to build applications using a real API and database. You'll leverage 3rd party APIs like Zomato, Google Places, and open-source libraries just as you would in a real job.

The Angular Tutorial assumes you have no previous knowledge of the Angular framework. It starts at the very beginning.

Every piece of code is explained and tested to make you interview ready.

Ready to get started? 👇