Skip to main content

A Basic Understanding On Angular Reactive Forms


In this article, I try to give a basic understanding of implementing the Angular Reactive Forms Sample. In Angular Forms can be implemented by using either Template Driven Forms Or Reactive Forms. Reactive Forms are more useful for complex forms.

Create A Sample Angular Project:

For better understanding let's understand the concept by making hands dirty by writing sample examples. So let's create a sample angular project.

If you have prior knowledge of creating Angular Application and configuring Angular Material(UI library) in to project, then free feel to skip this section.

Let's use Angular CLI commands to create a sample project.

Command to install Angular CLI:-
Command To Install Angular CLI globally.This command is like one time installation. If you already have Agnular CLI installed on you system then skip this command.

npm install -g @angular/cli
Command to create Angular application:-
ng new your-application-new
Application template looks as below
Now to run the application, open application using any IDE(I'm using Visual Studio Code). Then open the IDE internal Terminal command or open a normal command prompt and set the application root path. Then run the below command.
Command to run application:

ng serve

To configure Angular Material UI just run the below command.
ng add @angular/material

Import ReactiveFormModule:

The first basic step to use reactive forms is to import ReactiveFormModule in the app.module.ts file. ReactiveFormModule comes with one of the inbuild angular package '@angular/forms'. ReactiveFormModule provides all objects like 'FormControl', 'FormGroup', 'FormBuilder' which are needed to build reactive forms.

Let's import ReactiveFormModule in the app.module.ts as below
src/app/app.module.ts:
import { ReactiveFormsModule } from '@angular/forms';

@NgModule({
  imports: [ReactiveFormsModule],
})
export class AppModule {}
// display purpose existing code hidden

FormControl Object:

In reactive forms, FormControl instance gets loaded from the '@angular/forms' package. In reactive forms, an HTML field will have its FormControl instance to establish communication between angular component and HTML. FormControl instance provides many inbuilt features like validating fields, listen to field value changes, identifies the state of the field, etc.

Let's add FormControl instance in the app.component.ts
src/app/app.component.ts:
import { Component} from '@angular/core';
import { FormControl } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent{
  firstName:FormControl = new FormControl();
}
Since I'm using material design, I will use material UI form components. So before adding a form input value in Html. Let's import two material modules like 'MatFormFieldModule', 'MatInputModule'.
src/app/app.module.ts:
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';

@NgModule({
  imports: [
    MatFormFieldModule,
    MatInputModule
  ],
  providers: [],
  bootstrap: [],
})
export class AppModule {}
// display purpose existing code hidden
Now, let's add the input field and will assign FormControl instance to it.
src/app/app.component.html:
<div>
  <mat-form-field appearance="fill">
    <mat-label>First Name</mat-label>
    <input matInput [formControl]="firstName">
  </mat-form-field>
</div>
#L4 at this line for [formControl](can be called as FormControlDirective) assigned with 'firstName'(variable holding FormControl instance)

Now start the application and shows the output as below.

FormControl setValue Method:

To update the field value from the FormControl we can use the setValue method.
src/app/app.component.ts:
import { Component, OnInit} from '@angular/core';
import { FormControl } from '@angular/forms';

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

  firstName:FormControl = new FormControl();

  ngOnInit(): void {
    this.firstName.setValue('naveen');
  }
}
#L15 at this line updating the FormControl name which will reflect on to the field on page load.

Now run application and it shows the output as below.

FormControl Change Detection:

On changing the value on form field in Html, FormControl can respond to those changes. 'valueChanges' is an observable property on FormControl instance that capture the user changes. In real-time scenarios like search content cases, this change detection will help.
src/app/app.component.ts:
import { Component, OnInit} from '@angular/core';
import { FormControl } from '@angular/forms';

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

  firstName:FormControl = new FormControl();

  ngOnInit(): void {
    this.firstName.valueChanges.subscribe(value => {
      console.log(value);
    })
  }
}
#L15-L17 at these lines FormControl valuChanges observable get subscribe to capture the changed value from the user.

Now run the application and shows the output as below.

FormGroup Object:

In reactive forms, FormGroup instance gets loaded from the '@angular/forms' Package. In reactive forms FormGroup act as a container for a set of FormControl instances. So grouping controls can help to separate the existence of multiple numbers of forms on a single page or view.
src/app/app.component.ts:
import { Component } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  personFormGroup = new FormGroup({
    firstName:new FormControl(''),
    lastName : new FormControl(''),
    email: new FormControl(''),
    phone: new FormControl('')
  })
}
#L10-L15 at these lines FormGroup object created with the collection of FormField objects.
src/app/app.component.html:
<div style="margin:10px;">
  <form [formGroup]="personFormGroup">
    <div>
      <mat-form-field class="example-full-width">
        <mat-label>First Name</mat-label>
        <input matInput formControlName="firstName">
      </mat-form-field>
    </div>
    <div>
      <mat-form-field>
        <mat-label>Last Name</mat-label>
        <input matInput formControlName="lastName">
      </mat-form-field>
    </div>
    <div>
      <mat-form-field>
        <mat-label>Email</mat-label>
        <input matInput formControlName="email">
      </mat-form-field>
    </div>
    <div>
      <mat-form-field>
        <mat-label>Phone</mat-label>
        <input matInput formControlName="phone">
      </mat-form-field>
    </div>
  </form>
</div>
  • #L2 at this line [formGroup](can be called as FormGroupDirective) defined and assigned 'personFormGroup'(formGroup object). 
  • All input fields were decorated with 'formControlName'(can be called as FormControlDirective) and assigned 'formcontrol' instances that are inside of the FormGroup.
Now run the application and output shows as below.

Nested FormGroup:

FormGroup along with FormControl instances, it can also contain nested FormGroup. Nested FormGroup component gives nice separation for large or complex forms. A nested form state can override the state of main FormGroup(for example if nested form group is an invalid state, then the same state will be applied to the main FormGroup which helps to decide whether to submit the form or not).
src/app/app.component.ts:
import { Component } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  personFormGroup = new FormGroup({
    firstName:new FormControl(''),
    lastName : new FormControl(''),
    email: new FormControl(''),
    phone: new FormControl(''),
    address: new FormGroup({
      street : new FormControl(''),
      city: new FormControl(''),
      state: new FormControl('')
    })
  })
}
#L15-L19 at these lines nested FormGroup initialized.
src/app/app.component.html:
<div style="margin:10px;">
  <form [formGroup]="personFormGroup">
    <div>
      <mat-form-field class="example-full-width">
        <mat-label>First Name</mat-label>
        <input matInput formControlName="firstName">
      </mat-form-field>
    </div>
    <div>
      <mat-form-field>
        <mat-label>Last Name</mat-label>
        <input matInput formControlName="lastName">
      </mat-form-field>
    </div>
    <div>
      <mat-form-field>
        <mat-label>Email</mat-label>
        <input matInput formControlName="email">
      </mat-form-field>
    </div>
    <div>
      <mat-form-field>
        <mat-label>Phone</mat-label>
        <input matInput formControlName="phone">
      </mat-form-field>
    </div>
    <div formGroupName="address">
      <h4>Address</h4>
      <div>
        <mat-form-field>
          <mat-label>Street</mat-label>
          <input matInput formControlName="street">
        </mat-form-field>
        <mat-form-field>
          <mat-label>City</mat-label>
          <input matInput formControlName="city">
        </mat-form-field>
        <mat-form-field>
          <mat-label>State</mat-label>
          <input matInput formControlName="state">
        </mat-form-field>
      </div>
    </div>
  </form>
</div>
#L27 at this line 'address'(nested FormGroup instance variable) assigned to 'formGroupName'(can be called as FormGroupDirective).

Now run the application and shows outputs as below.

FormBuilder Object:

  • In reactive form, FormBuilder instance gets loaded from the '@angular/forms' package. 
  • FormBuilder instance is a factory object which can create instances for FormGroups or FormControls. 
  • For FormBuilder there is no limit in creating instances for FormGroups or FormControls. 
  • Using FormBuilder we can avoid explicit initialization of FormGroups or FormControls, this makes form looks clean and simple. 
  • FormBuilder Object also works with Dependency Injection where we can inject in the component constructor.
Let's update the component to use FormBuilder instance as follows.
src/app/app.component.ts:
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder } from '@angular/forms';

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

  constructor(private fBuilder: FormBuilder) {}

  ngOnInit(): void {
    this.initializeForm();
  }

  initializeForm() {
    this.personFormGroup = this.fBuilder.group({
      firstName:[''],
      lastName:[''],
      email:[''],
      phone: [''],
      address: this.fBuilder.group({
        street:[''],
        city:[''],
        state:['']
      })
    });
  }
}
  • #L13 at this line FormBuilder instance gets injected into the component constructor.
  • #L20-30 at these lines FormBuilder instance creating the FormGroup instance, we can observe explicitly initialization of FormControl or FormGroup avoided.
  • #L25-29 at these lines FormBuilder instance creating the new FormGroup instance to work as nested FormGroup. From this, we can understand there is no limit in creating FormGroups or FormControls by the FormBuilder instance.

FormGroup setValue:

To update the form with the value we can use the 'setValue' method. But on using the 'setValue' method, we need to update every FormControl value in the FormGroup. So set value will be the ideal technique for the initial page load, where we fetch data from the database(using APIs) to update the entire form.

Let's update the code to use the 'setValue' method as below.
src/app/app.component.ts:
setValueMethod(){
	this.personFormGroup.setValue({
	  firstName:'Naveen',
	  lastName: 'Bommidi',
	  email:'bommidi@gmail.com',
	  phone:'1234567890',
	  address:{
		street:'Arunoday colony',
		city:'hyderabad',
		state:'Telangana'
	  }
	});
}
#L2-L12 at these lines you can observe updating data to the entire sample form. We can observe using the 'setValue' method need to update every FormControl and FromGroup.

Let's create a test button to update all form values.
src/app/app.component.html:
<div style="margin:10px;">
  <form [formGroup]="personFormGroup">
		<!-- display purpose code hidden -->
  </form>
  <div>
    <button mat-raised-button color="primary" (click)="setValueMethod()">Update All Form values</button>
  </div>
</div>
#L6 at this line added a button and it clicks event registered with 'setValueMethod'.

Now let's run the application and output shows as below.
Now on clicking 'Update All Form values' button form get populated with data and shows as below.

FormGroup patchValue:

Since the setValue method only works for updating entire form values, it won't be an ideal technique to use in most cases. So update partially or whatever form controls to be updated then we should use 'patchValue'. For the 'patchValue' method there are no rules to update all form fields, it can update whatever field it wants.

Let's create a simple patchValue method as follows.
src/app/app.component.ts:
patchValueMethod(){
	this.personFormGroup.patchValue({
	  firstName:'Naveen',
	  address:{
		city:'Hyderabad'
	  }
	});
}
#L2-L7 at these lines FormGroup data patching for only 2 form controls.

Let's add a test button to invoke this patchValue method as follows.
src/app/app.component.html:
<div style="margin:10px;">
  <form [formGroup]="personFormGroup">
    <!-- code hidden for display purpose -->
  </form>
  <div>
    <button mat-raised-button color="primary" (click)="setValueMethod()">Update All Form values</button>
    <button mat-raised-button color="primary" (click)="patchValueMethod()">Update Only Specific Fields</button>
  </div>
</div>
#L7 at this line button added and it clicks event to bind to 'patchValueMethod'.

Now let's run the application and output shows as below.
Now click on button and output show as below.

Add Validation:

In reactive forms configuring validation is so simple and easy. Validation to a reactive form can be done at the time of form initialization or dynamically. Here we going to add validation at the time of initializing form.

Using 'Validators' instance which will get loaded from '@angular/forms' package. 'Validators' instance provide default validation like 'required', 'email', 'min length', 'max length', etc.

Let's update our form initialized method to register our validation as follows.
src/app/app.component.ts:
import { Validators } from '@angular/forms';

initializeForm() {
	this.personFormGroup = this.fBuilder.group({
	  firstName:['',Validators.required],
	  lastName:[''],
	  email:['', [Validators.required, Validators.email]],
	  phone: [''],
	  address: this.fBuilder.group({
		street:[''],
		city:[''],
		state:['']
	  })
	});
}
  • #L5 at this line number 'Validators.required' validation added to firstName FormControl.
  • #L7 at this line number array of Validators like 'required' and 'email' validations added to the email FormControl.
Let's add a sample form submission method in the app.component.ts file as below.
src/app/app.component.ts:
onSubmit(){
	if(this.personFormGroup.valid){
	   var formData = {
		 name: this.personFormGroup.controls.firstName.value,
		 lastName : this.personFormGroup.controls.lastName.value,
		 email : this.personFormGroup.controls.email.value,
		 phone: this.personFormGroup.controls.phone.value,
		 street: this.personFormGroup.get('address.street').value,
		 city: this.personFormGroup.get('address.city').value,
		 state: this.personFormGroup.get('address.state').value
	   }
	   // need to write post api call to save data
	}
}
Here this method will execute on submitting a valid form. Here you can also observe the way to fetch the data from FormControl and also from nested FormGroupControl.

Now let's add form submit button and bind this 'onSubmit()' method to the form as below
src/app/app.component.html:
<div style="margin:10px;">
  <form [formGroup]="personFormGroup" (ngSubmit)="onSubmit()">
    <!-- code hidden for display purpose -->
    <div>
      <button mat-raised-button color="primary" >Submit Form</button>
    </div>
  </form>
</div>
  • #L2 at this line using angular (onSubmit) form event bounded to our custom 'onSubmit()' method. so this (onSubmit) gets fired on the clicking a button inside the form.
  • #L5 at this line added button to invoke form submit.
Now run the application and output shows as below.
Click on the submit button, form validation executes and the output shows as below.

Wrapping Up:

Hopefully, I think this article delivered some useful information on angular reactive forms. I love to have your feedback, suggestions, and better techniques in the comment section below.

Follow Me:

Comments

  1. Your articles are very precise. Will be very helpful for beginners and even experienced people for simplicity of the content. Keep up the good work.

    ReplyDelete

Post a Comment

Popular posts from this blog

.NET6 Web API CRUD Operation With Entity Framework Core

In this article, we are going to do a small demo on AspNetCore 6 Web API CRUD operations. What Is Web API: Web API is a framework for building HTTP services that can be accessed from any client like browser, mobile devices, desktop apps. In simple terminology API(Application Programming Interface) means an interface module that contains a programming function that can be requested via HTTP calls to save or fetch the data for their respective clients. Some of the key characteristics of API: Supports HTTP verbs like 'GET', 'POST', 'PUT', 'DELETE', etc. Supports default responses like 'XML' and 'JSON'. Also can define custom responses. Supports self-hosting or individual hosting, so that all different kinds of apps can consume it. Authentication and Authorization are easy to implement. The ideal platform to build REST full services. Create A .NET6 Web API Application: Let's create a .Net6 Web API sample application to accomplish our

Angular 14 Reactive Forms Example

In this article, we will explore the Angular(14) reactive forms with an example. Reactive Forms: Angular reactive forms support model-driven techniques to handle the form's input values. The reactive forms state is immutable, any form filed change creates a new state for the form. Reactive forms are built around observable streams, where form inputs and values are provided as streams of input values, which can be accessed synchronously. Some key notations that involve in reactive forms are like: FormControl - each input element in the form is 'FormControl'. The 'FormControl' tracks the value and validation status of form fields. FormGroup - Track the value and validate the state of the group of 'FormControl'. FormBuilder - Angular service which can be used to create the 'FormGroup' or FormControl instance quickly. Form Array - That can hold infinite form control, this helps to create dynamic forms. Create An Angular(14) Application: Let'

Part-1 Angular JWT Authentication Using HTTP Only Cookie[Angular V13]

In this article, we are going to implement a sample angular application authentication using HTTP only cookie that contains a JWT token. HTTP Only JWT Cookie: In a SPA(Single Page Application) Authentication JWT token either can be stored in browser 'LocalStorage' or in 'Cookie'. Storing JWT token inside of the cookie then the cookie should be HTTP Only. The HTTP-Only cookie nature is that it will be only accessible by the server application. Client apps like javascript-based apps can't access the HTTP-Only cookie. So if we use authentication with HTTP only JWT cookie then we no need to implement custom logic like adding authorization header or storing token data, etc at our client application. Because once the user authenticated cookie will be automatically sent to the server by the browser on every API call. Authentication API: To implement JWT cookie authentication we need to set up an API. For that, I had created a mock authentication API(Using the NestJS Se

Unit Testing Asp.NetCore Web API Using xUnit[.NET6]

In this article, we are going to write test cases to an Asp.NetCore Web API(.NET6) application using the xUnit. xUnit For .NET: The xUnit for .Net is a free, open-source, community-focused unit testing tool for .NET applications. By default .Net also provides a xUnit project template to implement test cases. Unit test cases build upon the 'AAA' formula that means 'Arrange', 'Act' and 'Assert' Arrange - Declaring variables, objects, instantiating mocks, etc. Act - Calling or invoking the method that needs to be tested. Assert - The assert ensures that code behaves as expected means yielding expected output. Create An API And Unit Test Projects: Let's create a .Net6 Web API and xUnit sample applications to accomplish our demo. We can use either Visual Studio 2022 or Visual Studio Code(using .NET CLI commands) to create any.Net6 application. For this demo, I'm using the 'Visual Studio Code'(using the .NET CLI command) editor. Create a fo

A Small Guide On NestJS Queues

NestJS Application Queues helps to deal with application scaling and performance challenges. When To Use Queues?: API request that mostly involves in time taking operations like CPU bound operation, doing them synchronously which will result in thread blocking. So to avoid these issues, it is an appropriate way to make the CPU-bound operation separate background job.  In nestjs one of the best solutions for these kinds of tasks is to implement the Queues. For queueing mechanism in the nestjs application most recommended library is '@nestjs/bull'(Bull is nodejs queue library). The 'Bull' depends on Redis cache for data storage like a job. So in this queueing technique, we will create services like 'Producer' and 'Consumer'. The 'Producer' is used to push our jobs into the Redis stores. The consumer will read those jobs(eg: CPU Bound Operations) and process them. So by using this queues technique user requests processed very fastly because actually

Angular 14 State Management CRUD Example With NgRx(14)

In this article, we are going to implement the Angular(14) state management CRUD example with NgRx(14) NgRx Store For State Management: In an angular application to share consistent data between multiple components, we use NgRx state management. Using NgRx state helps to avoid unwanted API calls, easy to maintain consistent data, etc. The main building blocks for the NgRx store are: Actions - NgRx actions represents event to trigger the reducers to save the data into the stores. Reducer - Reducer's pure function, which is used to create a new state on data change. Store - The store is the model or entity that holds the data. Selector - Selector to fetch the slices of data from the store to angular components. Effects - Effects deals with external network calls like API. The effect gets executed based the action performed Ngrx State Management flow: The angular component needs data for binding.  So angular component calls an action that is responsible for invoking the API call.  Aft

Usage Of CancellationToken In Asp.Net Core Applications

When To Use CancellationToken?: In a web application request abortion or orphan, requests are quite common. On users disconnected by network interruption or navigating between multiple pages before proper response or closing of the browser, tabs make the request aborted or orphan. An orphan request can't deliver a response to the client, but it will execute all steps(like database calls, HTTP calls, etc) at the server. Complete execution of an orphan request at the server might not be a problem generally if at all requests need to work on time taking a job at the server in those cases might be nice to terminate the execution immediately. So CancellationToken can be used to terminate a request execution at the server immediately once the request is aborted or orphan. Here we are going to see some sample code snippets about implementing a CancellationToken for Entity FrameworkCore, Dapper ORM, and HttpClient calls in Asp.NetCore MVC application. Note: The sample codes I will show in

Blazor WebAssembly Custom Authentication From Scratch

In this article, we are going to explore and implement custom authentication from the scratch. In this sample, we will use JWT authentication for user authentication. Main Building Blocks Of Blazor WebAssembly Authentication: The core concepts of blazor webassembly authentication are: AuthenticationStateProvider Service AuthorizeView Component Task<AuthenticationState> Cascading Property CascadingAuthenticationState Component AuthorizeRouteView Component AuthenticationStateProvider Service - this provider holds the authentication information about the login user. The 'GetAuthenticationStateAsync()' method in the Authentication state provider returns user AuthenticationState. The 'NotifyAuthenticationStateChaged()' to notify the latest user information within the components which using this AuthenticationStateProvider. AuthorizeView Component - displays different content depending on the user authorization state. This component uses the AuthenticationStateProvider

How Response Caching Works In Asp.Net Core

What Is Response Caching?: Response Caching means storing of response output and using stored response until it's under it's the expiration time. Response Caching approach cuts down some requests to the server and also reduces some workload on the server. Response Caching Headers: Response Caching carried out by the few Http based headers information between client and server. Main Response Caching Headers are like below Cache-Control Pragma Vary Cache-Control Header: Cache-Control header is the main header type for the response caching. Cache-Control will be decorated with the following directives. public - this directive indicates any cache may store the response. private - this directive allows to store response with respect to a single user and can't be stored with shared cache stores. max-age - this directive represents a time to hold a response in the cache. no-cache - this directive represents no storing of response and always fetch the fr

Angular 14 Crud Example

In this article, we will implement CRUD operation in the Angular 14 application. Angular: Angular is a framework that can be used to build a single-page application. Angular applications are built with components that make our code simple and clean. Angular components compose of 3 files like TypeScript File(*.ts), Html File(*.html), CSS File(*.cs) Components typescript file and HTML file support 2-way binding which means data flow is bi-directional Component typescript file listens for all HTML events from the HTML file. Create Angular(14) Application: Let's create an Angular(14) application to begin our sample. Make sure to install the Angular CLI tool into our local machine because it provides easy CLI commands to play with the angular application. Command To Install Angular CLI npm install -g @angular/cli Run the below command to create the angular application. Command To Create Angular Application ng new name_of_your_app Note: While creating the app, you will see a noti