Angular Reactive Form

Introduction

Angular Forms is a powerful feature of the Angular framework that allows you to create complex forms that handle user input and perform validations. There are two types of forms in Angular: Template-driven forms and Reactive forms. In this answer, I will describe Reactive forms with an example. 

Reactive Forms  

Reactive forms use a model-driven approach to handle form inputs. You create a form model in your component that maps to the form controls in your template. This gives you more control over the form and allows you to create dynamic forms that can change based on user input. 

Here is an example of how to create a Reactive form in Angular.

First, you need to import the necessary modules into your component.

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

@Component({
  selector: 'app-example',
  template: `
    <form [formGroup]="myForm" (ngSubmit)="onSubmit()">
      <label>
        Name:
        <input type="text" formControlName="name">
      </label>
      <label>
        Email:
        <input type="email" formControlName="email">
      </label>
      <button type="submit">Submit</button>
    </form>
  `,
})
export class ExampleComponent {
  myForm: FormGroup;

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

  onSubmit() {
    console.log(this.myForm.value);
    // Do something with the form data
  }
}

In this example, we created a Reactive form with two form controls: name and email. The form model is defined in the ExampleComponent class using the FormGroup and FormControl classes. The Validators class defines the validation rules for each form control.

And must include FormsModule and ReactiveFormsModule in your Module.

In the template, we bind the form model to the formGroup directive and each form control to the formControlName directive.

When the user submits the form, the onSubmit method is called. You can access the form data using the value property of the form model.

Conclusion

Reactive forms give you more control over your form and allow you to create complex forms with dynamic validation rules. While they require more code to set up, they are more powerful and flexible than Template-driven forms.

Thanks For Reading 😊