AppDividend
Latest Code Tutorials

Angular Reactive Forms | Angular 9/8/7 Reactive Forms Example

0

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.

Difference between Template-driven forms and Model-driven forms(Reactive Forms)

Template Driven forms give us an easy way to get up and running, whereas Model-Driven allows you to take your forms wherever they need to go. module, instead of the Forms Module. We need to update the App Module to import and use that instead of the Forms Module.

Now, just so you know, it is possible to import both of these together in the case where your module is making use of both template and model-driven forms, or reactive forms.

Reactive forms differ from the template-driven forms in many ways. Reactive forms provide more predictability with synchronous access to a data model, immutability with observable operators, and change tracking through the observable streams.

If you prefer the direct access to modify data in your template, template-driven forms are less explicit because they rely on the directives embedded in the template, along with a mutable data to track changes asynchronously.

If you are new to Angular 9, then I highly recommend checking out the following tutorials.

Upgrade Angular 9 CLI

Angular 9 CRUD Example

Angular 9 Reactive Forms

Reactive forms use the explicit and immutable approach to managing the state of the form at a given point in time. Each change to the form state returns the new state, which maintains integrity of the model between changes.

Reactive forms are built around observable streams, where the form inputs and values are provided as streams of input values, which can be accessed synchronously.

Reactive forms also provide a straightforward path to testing because you are assured that your data is consistent and predictable when requested. Any consumers of the streams have access to manipulate that data safely.

We are going to create a form group object. Remember form from the template-driven approach, that the Angular form system is working with a form group, in the Angular forms scoped package. We need a class property for the form.

This section describes how to add a single form control. In the example, the user enters their name into an input field, captures that input value, and displays the current value of the form control element.

Let’s learn how to use Reactive Forms in Angular 9.

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.

Just as a form control instance gives you control over a single input field, a form group instance tracks the form state of a group of form control instances (for example, a form). Each control in a form group instance is tracked by name when creating the form group.

To leverage a life-cycle event, you just need to add a known function name to your class, and Angular will handle calling it if it exists in your class. 

We can also make use of a typescript interface here, name OnInit, that Angular provides to help enforce the implementation. So lets on OnInit to the import statement from Angular core. Then add implements OnInit after the class name. Then we can add a ngOnInit method.

We will create two form fields, which are the following.

1) patient_name

2) patient_age

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. 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. By creating these controls in your component class, you get immediate access to listen for, update, and validate the state of the form input.

For this example, I will not use Constructor, but I will use 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 you create a control in the component class, you must associate it with the form control element in the template. 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>

First, we need to tell Angular that we have a model for the form. So in the form group bracket, Setting that equal to form or whatever the name you like.

Using a template binding syntax, the form control is now registered to the patient_name and patient_age input element in the template.

The form control and DOM elements communicate with each other: the view reflects changes in the model, and the model reflects the changes in the view.

Step 4: Add form submit the form

Now, 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>

So, when a user clicks the submit button, we get all the values of form elements and sent 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);
  }
}

Here, we got the form data.

If we want to send it to the server, then we can use the HttpClientModule provided by Angular 9 to send the network request to the server.

Conclusion

To implement Reactive Forms in Angular 9, we follow the below steps.

  1. Import the Reactive Form Module in the app.module.ts file.
  2. Create an instance of FormGroup class in the component file and initialize the default values of all FormControls.
  3. Bind the FormGroup and FormConrtol in the HTML code.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.