How to Reset Forms in Angular 2

  1. Understanding ngForm
  2. Method 1: Using the resetForm() Method
  3. Method 2: Resetting Form with Initial Values
  4. Method 3: Resetting Form Controls Individually
  5. Conclusion
  6. FAQ
How to Reset Forms in Angular 2

Resetting forms in Angular 2 is a fundamental skill for developers looking to create user-friendly applications. Forms are integral to gathering user input, and at times, you may need to reset these forms to their initial state. Whether it’s due to a user canceling their input or simply wanting to start over, knowing how to effectively reset forms can significantly enhance user experience.

In this article, we’ll delve into various methods to reset forms in Angular 2, focusing on the powerful ngForm directive. We’ll explore practical examples and provide clear explanations to ensure you can implement these techniques in your own projects. By the end, you’ll have a solid understanding of how to reset forms efficiently, making your Angular applications more robust and user-friendly.

Understanding ngForm

Before we dive into the methods for resetting forms, it’s essential to understand what ngForm is. This directive is part of Angular’s reactive forms module, which provides a way to manage form inputs and their states. When you use ngForm, Angular creates a form object that tracks the value and validity of each form control. This makes it easier to manage user input and perform actions like resetting the form.

When a form is reset, all the controls within it return to their initial state. This includes clearing the input fields and resetting validation states. By leveraging ngForm, you can quickly implement a reset functionality that enhances your application’s usability.

Method 1: Using the resetForm() Method

One of the simplest ways to reset a form in Angular 2 is by using the resetForm() method provided by the ngForm directive. This method is straightforward and allows you to reset all form controls back to their initial values with just a single line of code.

Here’s how you can implement it:

import { Component } from '@angular/core';
import { NgForm } from '@angular/forms';

@Component({
  selector: 'app-reset-form',
  template: `
    <form #myForm="ngForm" (ngSubmit)="onSubmit(myForm)">
      <input name="username" ngModel required>
      <input name="email" ngModel required>
      <button type="submit">Submit</button>
      <button type="button" (click)="resetForm(myForm)">Reset</button>
    </form>
  `
})
export class ResetFormComponent {
  onSubmit(form: NgForm) {
    console.log('Form Submitted!', form.value);
  }

  resetForm(form: NgForm) {
    form.resetForm();
  }
}

Output:

Form Submitted! { username: 'JohnDoe', email: 'john@example.com' }

In this example, we have a simple form with two inputs: username and email. When the user clicks the “Reset” button, the resetForm() method is called. This method takes the form instance as an argument and invokes the resetForm() method on it. This action clears all input fields and resets their validation states, providing a clean slate for the user.

Method 2: Resetting Form with Initial Values

Sometimes, you may want to reset the form to specific initial values instead of just clearing the fields. Angular’s resetForm() method allows you to pass an object with the desired values. This is particularly useful when you want to restore default values after a user has made changes.

Here’s an example of how to achieve this:

import { Component } from '@angular/core';
import { NgForm } from '@angular/forms';

@Component({
  selector: 'app-reset-with-values',
  template: `
    <form #myForm="ngForm" (ngSubmit)="onSubmit(myForm)">
      <input name="username" ngModel required>
      <input name="email" ngModel required>
      <button type="submit">Submit</button>
      <button type="button" (click)="resetForm(myForm)">Reset to Defaults</button>
    </form>
  `
})
export class ResetWithValuesComponent {
  defaultValues = { username: 'DefaultUser', email: 'default@example.com' };

  onSubmit(form: NgForm) {
    console.log('Form Submitted!', form.value);
  }

  resetForm(form: NgForm) {
    form.resetForm(this.defaultValues);
  }
}

Output:

Form Submitted! { username: 'JohnDoe', email: 'john@example.com' }

In this code, we define an object defaultValues that holds the initial values we want to reset the form to. When the user clicks the “Reset to Defaults” button, the resetForm() method is called with this.defaultValues as an argument. As a result, the form fields are populated with the specified default values instead of being cleared. This method provides flexibility in managing form states and enhances the overall user experience.

Method 3: Resetting Form Controls Individually

In some scenarios, you may want to reset individual form controls instead of the entire form. Angular provides a way to access each control via the form.controls property. This method allows you to selectively reset controls based on your application’s needs.

Here’s how you can implement this approach:

import { Component } from '@angular/core';
import { NgForm } from '@angular/forms';

@Component({
  selector: 'app-reset-individual-controls',
  template: `
    <form #myForm="ngForm" (ngSubmit)="onSubmit(myForm)">
      <input name="username" ngModel required>
      <input name="email" ngModel required>
      <button type="submit">Submit</button>
      <button type="button" (click)="resetUsername(myForm)">Reset Username</button>
    </form>
  `
})
export class ResetIndividualControlsComponent {
  onSubmit(form: NgForm) {
    console.log('Form Submitted!', form.value);
  }

  resetUsername(form: NgForm) {
    form.controls['username'].reset();
  }
}

Output:

Form Submitted! { username: 'JohnDoe', email: 'john@example.com' }

In this example, we have a form with two fields: username and email. When the user clicks the “Reset Username” button, the resetUsername() method is invoked. This method accesses the username control via form.controls['username'] and calls the reset() method on it. This action clears the username field while leaving the email field untouched, allowing for more granular control over the form state.

Conclusion

Resetting forms in Angular 2 is a straightforward process that can significantly improve user experience. By utilizing methods like resetForm(), resetting to specific values, and resetting individual controls, you can create dynamic and responsive forms tailored to your application’s needs. These techniques not only enhance usability but also ensure that your forms remain robust and reliable.

As you continue to build your Angular applications, mastering form management will empower you to create seamless user interactions. Remember to explore the various methods discussed in this article, and consider implementing them in your projects for a more polished user experience.

FAQ

  1. What is ngForm in Angular?
    ngForm is a directive in Angular that helps manage form inputs and their states. It tracks the value and validity of each form control.

  2. How do I reset a form in Angular 2?
    You can reset a form in Angular 2 using the resetForm() method provided by the ngForm directive.

  3. Can I reset a form to specific initial values?
    Yes, you can pass an object with the desired initial values to the resetForm() method to reset the form to those values.

  4. How can I reset individual form controls?
    You can access individual form controls using the form.controls property and call the reset() method on the specific control you want to clear.

  5. Why is resetting forms important in Angular applications?
    Resetting forms is important for enhancing user experience, allowing users to easily start over, and ensuring that the form state is managed effectively.

Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
Muhammad Adil avatar Muhammad Adil avatar

Muhammad Adil is a seasoned programmer and writer who has experience in various fields. He has been programming for over 5 years and have always loved the thrill of solving complex problems. He has skilled in PHP, Python, C++, Java, JavaScript, Ruby on Rails, AngularJS, ReactJS, HTML5 and CSS3. He enjoys putting his experience and knowledge into words.

Facebook

Related Article - Angular Form