AngularJS (62 Blogs) Become a Certified Professional

What are the Reactive Forms in Angular? – Explained With Examples

Last updated on Sep 09,2024 42 Views

Sunita Mallick
Experienced tech content writer passionate about creating clear and helpful content for... Experienced tech content writer passionate about creating clear and helpful content for learners. In my free time, I love exploring the latest technology.

Template-driven forms and Reactive Forms are two fundamental ways to build web application forms in Angular, a popular framework for building web applications. Both will produce similar results, but Angular Reactive Forms are the more comprehensive and scalable method for a form that is doing just about anything. The good, the bad, and the ugly: All too often, we hear that Angular Reactive Forms are better than template-driven ones. Let’s see if that’s true or not.

Reactive Forms

Angular Reactive Forms, as their name implies, are based on reactive programming. Instead of using the template (HTML) to manage form state, Reactive Forms uses TypeScript code in your Angular components to define and control an instance of a class directly.

Key Features of Angular Reactive Forms:

  1. Component-Centric: Reactive Forms primarily work with the component class. The form controls are implemented as objects in the TypeScript code of a component and provide well-separated responsibilities between the template and business logic parts of a declaration.
  2. Immutability: Form values are treated as immutable objects for better performance. Code-wise, the form value properties won’t change. Technically, all attributes of control are anonymous strings that will convert to something in server-side code if there is any such field matched. This way, every update to form data will categorically create a new set of values, easily detect changes and help maintain consistent states across the framework.
  3. Observables: Reactive Forms work with RxJS Observables, and our forms are essentially a stream of observable values. This reactive nature allows for real-time responses to user input and smooth UI integration with other Angular functionality.
  4. Extensibility: Reactive Forms give developers flexibility. They can create any type of validation rules (custom) and react to complex form interactions easily, as well as have dynamic forms based on user action.

Template-driven Forms

Reactive Forms go a long way; Angular also provides template-driven forms. The most common use case is to interact with a standard user input—it’s an easy directive such as ngModel. Template-driven forms may be easier to handle for simple use cases but have more limited capabilities and offer less granularity than Reactive Forms.

Key Features of Template-driven Forms:

  1. Simplicity: Template-driven forms are simpler to set up, making them a great fit for straightforward and smaller applications.
  2. Two-way Data Binding: Use two-way data binding of Angular to make the form model and view stay synchronized.
  3. Model-View Synchronisation: Template-driven forms feature one-way or two-way automatic synchronization with models.
  4. Built-in Validators: Angular provides a variety of validators built right into the template.

Also Read What are the Reactive Forms in Angular

Which is Better, Reactive or Template-driven?

Here is how you can choose between Reactive Forms and Template-driven forms according to your needs:

  1. Reactive Forms: Advantages of Reactive Forms are preferable when you have complex form requirements, such as dynamic inputs or large-scale invalidation logic.
  2. Template-driven Forms: These would be great for simpler forms with simple validation needs that use the more templating style.

When do we Use Reactive Forms

Reactive Forms are most powerful in these use cases:

  • Complex Structures: Forms and more complex structures with sub-forms, conditional fields, or dynamic elements.
  • Advanced Validation: Forms that require complex field rules, cross-field validation, or asynchronous (AJAX/REST API) service-driven authorization.
  • Live Updates: Input forms that must react in real-time to user input and update other areas of the application.
  • Large Applications: Projects that require maintainability, testability, and scalability.

Reactive Forms Usage

Reactive Forms require extra code for importing modules, defining form controls, and managing the overall state of a form (validation).

Import ReactiveFormsModule: To use Reactive Forms, first import the ReactiveFormsModule in the Angular module where the form will be used.

import { ReactiveFormsModule } from '@angular/forms';

Define Form Controls: Create form controls using FormControl, FormGroup, or FormArray and define the form model.

import { FormControl, FormGroup, FormArray } from '@angular/forms';

this.form = new FormGroup({
  name: new FormControl(''),
  email: new FormControl(''),
  addresses: new FormArray([
    new FormGroup({
      street: new FormControl(''),
      city: new FormControl(''),
    }),
  ]),
});

Bind Form Controls to Template: In the template, bind the form controls to the respective form elements using Angular’s form directives, such as [formControl] and [formGroup].

<form [formGroup]="form" (ngSubmit)="onSubmit()">
  <label for="name">Name</label>
  <input id="name" formControlName="name" />
  
  <label for="email">Email</label>
  <input id="email" formControlName="email" />

  <div formArrayName="addresses">
    <div *ngFor="let address of form.get('addresses').controls; let i = index" [formGroupName]="i">
      <label for="street">Street</label>
      <input id="street" formControlName="street" />
      
      <label for="city">City</label>
      <input id="city" formControlName="city" />
    </div>
  </div>

  <button type="submit">Submit</button>
</form>

Handle Form Submission: Manage the form submission and handle the form data in the component.

onSubmit() {
  console.log(this.form.value);
}

Create a Reactive Forms Component

Creating a Reactive Forms component involves defining the form model, binding it to the template, and managing the form state. Here is a step-by-step guide to creating a Reactive Forms component:

Step 1: Import Necessary Modules: Import the ReactiveFormsModule and other necessary modules in your Angular module.

import { ReactiveFormsModule } from '@angular/forms';
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

[javascript]@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, ReactiveFormsModule],
  providers: [],
  bootstrap: [AppComponent],
})
export class AppModule {}

Step 2: Define the Component: Create a component and define the form model using FormGroup and FormControl.

import { Component } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  form: FormGroup;

  constructor() {
    this.form = new FormGroup({
      name: new FormControl(''),
      email: new FormControl(''),
    });
  }

  onSubmit() {
    console.log(this.form.value);
  }
}

Step 3: Bind the Form to the Template: In the component’s template, bind the form model to the form elements using Angular’s form directives.

<form [formGroup]="form" (ngSubmit)="onSubmit()">
  <label for="name">Name</label>
  <input id="name" formControlName="name" />
  
  <label for="email">Email</label>
  <input id="email" formControlName="email" />
  
  <button type="submit">Submit</button>
</form>

 

Step 4: Manage Form State and Validation: Optionally, you can add validation rules and manage the form state accordingly.

import { Validators } from '@angular/forms';

this.form = new FormGroup({
  name: new FormControl('', [Validators.required]),
  email: new FormControl('', [Validators.required, Validators.email]),
});

onSubmit() {
  if (this.form.valid) {
    console.log(this.form.value);
  } else {
    console.log('Form is invalid');
  }
}

Key Benefits of Reactive Forms

Most developers prefer Reactive Forms to template-driven forms because they offer multiple benefits:

  1. More Testable: Because Reactive Forms are model-driven, they can be tested more easily. This makes it easy to write unit tests for form controls, validation logic, and overall form submission.
  2. Scalability: Reactive Forms provide a more scalable and maintainable solution to manage the state of complex form requirements. It also removes the form logic from your template, improving refactoring and simplifying changes in behavior without affecting the UI.
  3. Flexibility: Reactive Forms are more flexible regarding validation and complex form structures. Adding or removing form controls on the fly is straightforward, and creating custom validators and other complex validation scenarios is not daunting.
  4. Performance: Reactive Forms can provide better performance in some cases, especially with larger forms or frequent updates.

Also read Alert in React Native with Example

Best Practices for Reactive Forms

In your Angular projects, adhere to these best practices to ensure that Reactive Forms function at their peak:

  1. Use FormBuilder: Use the FormBuilder service to group controls and form-related code in your components. This makes the code neater.
  2. Group Related Controls: Group-related controls form nested groups to increase the coherence and structure of your forms.
  3. Use Built-in Validators: Angular comes with a set of built-in validations for standard cases such as required fields, correct email, or minimum/maximum length. Whenever possible, use these validators to minimize boilerplate code.
  4. Use Custom Validators: If you have more specific validation requirements, create custom validators to enforce your application business rules.
  5. Catch Form Errors: Display helpful and informative error messages to users who submit malformed data. Use the formControl to notice client-side errors that can be reached within each control validated via the .errors property.
  6. Subscribe to ValueChanges: Use the valueChange Observable and listen for changes in form values. This way, you can update some other part of your application or perform another action on user input.

Advanced Reactive Forms Techniques

Some advanced forms are beyond what most people know. In such scenarios, you can utilize the following complex form-handling techniques available only with Reactive Forms:

  1. Dynamic Form Controls: Add and remove form controls dynamically based on user interactions or conditions.
  2. Nested Form Groups: Use form groups within other form groups for more complex data structures or to group-related controls.
  3. Library for Custom Form Controls: If you often need custom form controls, put them in a library and reuse them everywhere with just an import. Build simple-to-use custom form controls to encapsulate complex UI elements or behavior on regular controls.
  4. Asynchronous Validation: This feature helps check unique usernames with a server-side API endpoint validation.
  5. Value Transformers: Use value transformers to override the values of form controls before they are committed or presented.

With these advanced techniques, you will be able to create very complete forms and adapt them better for Angular.

Conclusion

Angular Reactive Forms are more robust and provide a flexible way to manage form controls and value changes in the control inputs. Reactive Forms are great for complex, scalable, and reactive form scenarios where you need synchronous access to the data model or require custom component validation rules. By following the simple steps explained above, you can successfully implement Reactive Forms in your Angular applications and handle forms easily. 

Angular Reactive Forms provides a model-driven approach to handling form input whose values change over time, whether it is because the user typed into an input box or used built-in browser UI like date pickers and dropdowns. Whether you are working on a simple form, such as getting feedback from your users or creating complex multi-step workflows like quote generation for home insurance policies, these sets of APIs provide the flexibility and modularity every Angular developer needs!

 

Upcoming Batches For Angular Certification Training Course Online
Course NameDateDetails
Angular Certification Training Course Online

Class Starts on 21st September,2024

21st September

SAT&SUN (Weekend Batch)
View Details
Angular Certification Training Course Online

Class Starts on 12th October,2024

12th October

SAT&SUN (Weekend Batch)
View Details
Comments
0 Comments

Join the discussion

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.

image not found!
image not found!

What are the Reactive Forms in Angular? – Explained With Examples

edureka.co