How To Use Reactive Forms in Angular

nitish96
Nitish Sharma
Published on: November 9, 2024
Updated on: November 14, 2024
How To Use Reactive Forms in Angular blog

Angular provides Two types of forms: template-driven forms and reactive forms. Template-driven forms are the default way to work with forms in Angular. With template-driven forms, template directives are used to build an internal representation of the form. With reactive forms, you build your own representation of the component class.

Reactive forms in Agular are used to manage the state of form inputs in a reactive way.

   FormGroup: Represents a group of form controls. It aggre4gates the values of each control into a single object.

   FormControl: Represents a single input field – a form control instance manages the value, validation status, and user interactions of an input field.

  FormBuilder: A service that provides convenient methods for creating instance of FormGroup and FormControl.

 Validators: Functions used for synchronous and asynchronous validation of form controls.

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsComponent } from './forms.component';
import { RouterModule, Routes } from '@angular/router';
import { ReactiveFormsModule } from '@angular/forms';
const routes:Routes = [

  {

    path:'', component:FormsComponent

  }

]

@NgModule({

  declarations: [FormsComponent],

  imports: [

    CommonModule,

    RouterModule.forChild(routes),

    ReactiveFormsModule

  ]

})
export class FormsModule { }

In this example, we have import ReactiveFormsModule in imports and also add forms component in declarations.

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

import { FormBuilder, FormGroup, Validators } from '@angular/forms';

 

@Component({

  selector: 'app-forms',

  templateUrl: './forms.component.html',

  styleUrls: ['./forms.component.scss']

})

export class FormsComponent implements OnInit {

forms$:FormGroup;

isSubmit:boolean = false;

  constructor(private fb:FormBuilder) {

    this.form();

  }

 

  ngOnInit(): void {

  }

 

  form(){

    this.forms$ = this.fb.group({

      name:['', Validators.required],

      email:['', [Validators.required, Validators.email]],

      phone:['', Validators.required]

    })

  }
<div class="container">

  <form [formGroup]="forms$" (ngSubmit)="submit()">

    <div class="mb-2 form-group">

      <label class="form-label">Name</label>

      <input type="text" class="form-control" formControlName="name" />

    </div>

    <div class="mb-2 form-group">

      <label class="form-label">Email</label>

      <input type="email" class="form-control" formControlName="email">

    </div>

    <div class="mb-2 form-group">

      <label class="form-label">Phone</label>

      <input type="text" class="form-control" formControlName="phone" />

    </div>

    <div class="text-center">

      <button type="submit" class="btn btn-success">Submit</button>

    </div>

  </form>

 

</div>

Form$: A FormGroup instance representing the form model.

isSubmit: A Boolean used to track the submission state of the form, set to false initially.

FormBuilder: It is service is inject to the constructor to simplify form creation.

We have createa form with three formControl – name, email and phone.

HTML Form Declaration

·       The form is defined with Angular’s formGroup directive, which binds it to forms$.

·       (ngSubmit)=”submit()” binds the form’s submission to s submit method.

·       A formControlName directive linking It to the respective form control in forms$.

Handle Form Validation

Validation is added to each form field with custom error messages shown when a field’s validation.

// all getter function

get name(){
  return this.forms$.get('name') as FormControl;
}
get email(){
  return this.forms$.get('email') as FormControl;
  }

get phone(){
  return this.forms$.get('phone') as FormControl;
  }

Create all fields getter functions, so that we can easy access to each form control from the HTML template.

<div class="container">
  <form [formGroup]="forms$" (ngSubmit)="submit()">
    <div class="mb-2 form-group">
      <label class="form-label">Name</label>
      <input type="text" class="form-control" formControlName="name" />
      <span class="text-danger" *ngIf="name.invalid && name.touched || isSubmit">
        <span *ngIf="name.hasError('required')">Name is required.</span>
      </span>

    </div>

    <div class="mb-2 form-group">
      <label class="form-label">Email</label>
      <input type="email" class="form-control" formControlName="email" />
      <span class="text-danger" *ngIf="email.invalid && email.touched || isSubmit">
        <span *ngIf="email.hasError('required')">Email is required.</span>
        <span *ngIf="email.hasError('email')">Email is not valid.</span>
      </span>

    </div>

    <div class="mb-2 form-group">
      <label class="form-label">Phone</label>
      <input type="text" class="form-control" formControlName="phone" />
      <span class="text-danger" *ngIf="phone.invalid && phone.touched || isSubmit">
        <span *ngIf="phone.hasError('required')">Phone is required.</span>
      </span>

    </div>

    <div class="text-center">
      <button type="submit" class="btn btn-success">Submit</button>

    </div>

  </form>

</div>

The control is invalid and has been interacted with (touched). isSubmit is true, meaning the form has been submitted without all required fields.

The isSubmit Boolean is a useful property to mark that the form was submitted. If the form is submitted without fulfil all fields validation, isSubmit can trigger error messages even if a user has not interacted with  each field.

Comments

Login to leave a comment.

Build Software Application with Impact Hive