Angular - Reactive Forms



Reactive Forms in Angular

Reactive Form is a type of Angular form that manages the form state using an immutable approach. Here, immutable means each change to the form state returns a new version of the state.

Reactive forms are created inside the component class and are also referred to as model-driven forms. Every form control used within these forms has a separate object in the component class, which helps developers access and manage the data received from user input.

Let's understand how to use Reactive Forms in angular.

Classes of Angular Reactive Forms

Before moving to create Reactive forms, we need to understand the use of following classes −

  • FormControl: Define the basic functionality of individual form control.

  • FormGroup: Used to aggregate the values of form control collection.

  • FormArray: Used to aggregate the values of form control into an array.

  • ControlValueAccessor: Acts as an interface between Forms API and HTML DOM elements.

Creating Angular Reactive Forms

You can create an Angular reactive form in the four simple steps given below −

  • Step 1: First, import ReactiveFormsModule, FormGroup, FormControl from the @angular/forms package.

  • Step 2: Instantiate FormGroup and FormControl inside your component's TypeScript file (e.g., app.component.ts).

  • Step 3: Now, open component's HTML template (e.g., app.component.html) and bind the form using formGroup.

  • Step 4: At the end, use formControlName to bind each individual input field to the corresponding form control.

Example

Let us create a sample application (reactive-form-app) in Angular to learn the reactive form. Here, we create a simple reactive form to display user-entered text.

Step 1: Open the command prompt and create a new Angular application using the below command −

ng new reactive-form-app

Step 2: As mentioned earlier, import FormGroup, FormControl and ReactiveFormsModule in app.component.ts file.

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, ReactiveFormsModule } from '@angular/forms';
import { RouterOutlet } from '@angular/router';
import { CommonModule } from '@angular/common';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [RouterOutlet, ReactiveFormsModule, CommonModule],
  templateUrl: './app.component.html',
  styleUrl: './app.component.css'
})
export class AppComponent implements OnInit {
  title = 'form-app';
  userName: string = ""; 
  formdata: FormGroup = new FormGroup({});
  ngOnInit() { 
    this.formdata = new FormGroup({ 
      userName: new FormControl("") 
    }); 
  } 
  onClickSubmit(data: { userName: string }) { 
    this.userName = data.userName; 
  }
}

Here,

  • Created an instance of formGroup and set it to a local variable, formdata.

  • Created an instance of FormControl and set it to one of the entry in formdata.

  • Created a onClickSubmit() function, which sets the local variable, userName with its argument.

Step 3: Add the below code in app.component.html file.

<div> 
  <form [formGroup]="formdata" (ngSubmit)="onClickSubmit(formdata.value)" > 
     <input class="input-box" type= "text"  name="userName" placeholder="Enter Text" 
        formControlName = "userName"> 
     <input class="btn" type="submit"  value="Click here"> 
  </form>
</div> 
<p>You have entered: {{userName}} </p>

Here,

  • New form is created and its formGroup property is set to formdata.

  • New input text field is created and formControlName is set to username.

  • ngSubmit event property is used in the form and onClickSubmit() function is set as its value.

  • onClickSubmit() function gets formdata values as its arguments.

Step 4: Open app.component.css and add the code as specified below −

div {
    height: 100px;
    margin-top: 25px;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: rgb(165, 223, 204);
}
.input-box {
    margin: 10px;
    padding: 5px 15px;
    border-color: rgb(103, 220, 181);
}
.btn {
    padding: 5px 15px;
    color: white;
    font-weight: bold;
    background-color: rgb(103, 220, 181);
}
p { 
    font-weight: bold;
    margin-top: 10px;
}

Step 5: Finally, start your application using the below command −

ng serve

On running the application, the following output will be displayed −

Angular Reactive Form

Enter any text in the input field and press submit button. The onClickSubmit() function will be called and user-entered text will be sent as an argument and displayed on the screen.

Flow of Data in Reactive Forms

In the case of reactive forms, the form elements defined within the view are directly associated with the FormControl instance. However, any update from the view to the form model and from the model to the view does not depend on the user interface.

In reactive forms, the data flows in two ways as shown below −

  • View to Model
  • Model to View

View-to-Model Flow Diagram

The diagram given below shows the view-to-model data flow. This means how data flows when value of an input field is changed from the view.

Angular Reactive Form View to Model Diagram

Suppose a user types a value or makes a selection through the input element. This input element emits an input event with the latest value. Then, the ControlValueAccessor, which listens for events, immediately relays the new value to the FormControl instance. Next, the FormControl instance generates the new value through the valueChanges observable. In the end, the new value will be received by all subscribers of the valueChanges observable.

Model-to-View flow diagram

The diagram given below shows the model-to-view data flow. This means how data flows from model to view when logic is changed.

Reactive Form Model to View Diagram

First, the user calls the setValue() method, which updates the FormControl value. Then, the instance of FormControl generates the new value through the valueChanges observable. Now, the new value is received by the subscribers of the valueChanges observable. Lastly, the ControlValueAccessor will update the element with the new value.

Advertisements