Angular Reactive Forms: How to Use Reactive Forms in Angular

Angular Reactive Forms or Model-Driven approach is another way to construct forms in Angular. In Angular Reactive Forms, the form is built in the component class. That allows you to have a contract that your form subscribes to field-value changes, and ultimately unit-test your form logic without any UI layer.

In this tutorial, we will learn how to use reactive forms in Angular. To use reactive forms in Angular we follow these steps.

  • Step 1: Registering the Reactive Forms module
  • Step 2: Configure FormGroup and FormControl
  • Step 3: Registering the control in the template
  • Step 4: Adding submit an event to the form

Step 1: Registering the Reactive Forms module

To use reactive forms, import ReactiveFormsModule from the @angular/forms package and add it to your NgModule’s imports array.

// app.module.ts

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

@NgModule({
  imports: [
    // other imports ...
    ReactiveFormsModule
  ],
})
export class AppModule { }

Step 2: Configure FormGroup and FormControl

Write the following code inside the app.component.ts file.

// app.component.ts

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

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

The FormControl class is the basic building block when using reactive forms. To register a single form control, import the FormControl class into your component, and create a new instance of the form control to save as a class property.

The individual form controls are now collected within a group. A FormGroup instance provides its model value as an object reduced from the values of each control in the group. Thus, a form group instance has the same properties (such as value and untouched) and methods (such as setValue()) as a form control instance.

You can also use the Constructor of FormControl to set its initial value, which in this case, is an empty string. Creating these controls in your component class gives you immediate access to listen for, update, and validate the form input state.

For this example, I will not use Constructor, but the Life cycle method called ngOnInit() method.

// app.component.ts

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  form: FormGroup;
  ngOnInit() {
    this.form = new FormGroup({
      patient_name: new FormControl(''),
      patient_age: new FormControl(''),
    });
  }
}

We have set the initial value of patient_name and patient_age to empty.

Step 3: Registering the control in the template

After creating control in the component class, you must associate it with the form control element in the template. Then, update the template with a form control using the formControl binding provided by the FormControlDirective included in ReactiveFormsModule.

Write the code inside the app.component.html file.

<form [formGroup] = "form">
  <input type = "text" 
    name = "patient_name" 
    placeholder = "name" 
    formControlName = "patient_name">
  <br/>
  <input type = "text" 
    name = "patient_age" 
    placeholder = "age" 
    formControlName = "patient_age">
  <br/>
  <input type = "submit" value = "submit">
</form>

Step 4: Adding submit an event to the form

Add the ngSubmit() event in the form.

<form [formGroup] = "form" (ngSubmit) = "onClickSubmit(form.value)" >
  <input type = "text" 
    name = "patient_name" 
    placeholder = "name" 
    formControlName = "patient_name">
  <br/>
  <input type = "text" 
    name = "patient_age" 
    placeholder = "age" 
    formControlName = "patient_age">
  <br/>
  <input type = "submit" value = "submit">
</form>

When a user clicks the submit button, we get all the values of form elements and send them to the server.

At last, create a function called onClickSubmit(form.value) inside the app.component.ts file.

// app.component.ts

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  form: FormGroup;
  ngOnInit() {
    this.form = new FormGroup({
      patient_name: new FormControl(''),
      patient_age: new FormControl(''),
    });
  }
  onClickSubmit(formData) {
    console.log('Coronal Effected Patient name is : ' + formData.patient_name);
    console.log('Coronal Effected Patient age is : ' + formData.patient_age);
  }
}

You have now received the form. To send it to the server, we can use HttpClientModule Angular to send the network request to the server.

#angular

Angular Reactive Forms: How to Use Reactive Forms in Angular
2.00 GEEK