Template Driven & Reactive Forms - Angular "An Overview"

Profile picture for user Web Team
Designation
Developer

Web Team

Developer

Angular Forms

Template Driven & Reactive Forms Approaches

Why we need Forms:

              Forms are widely used in applications for user login purposes, to upload some information, update profiles, apply for different fields, and to perform more data entry tasks. Also, validation, recording user inputs, and showing error messages can be achieved. 

With respect to the handling of shapes, Angular has two approaches 

1. Template-Driven Forms 
2. Reactive Forms

Both the above approaches have few common building blocks holding the following attributes,

FormControl:
FormControl is used mainly for monitoring user input and authentication of the individual form control.

FormGroup: 
FormGroup used to track the same values and authentication status for a collection of a form of control.

FormArray:
FormArray tracks the same values and status for the array of the form control.

ControlValueAccessor:
ControlValueAccessor is used to develop a distance between Angular native DOM and form control elements.

More On Template-driven forms
   
Template-driven forms get it easy to create simple apps in an application like an email list signup form. Each and every field will have a separate individual binding in Template-driven forms.

Let us get deep into the procedure to create a simple registration form

1. To generate a component using the command.

 

Image removed.

 

(or)

 

Image removed.

 

2. In order to enable Template-driven forms, one suppose to import the “FormsModule” specific in app.module.ts

 

Image removed.

 

3. Creation of a simple registration form using template-driven

Image removed.


ngModel :

       The form input fields use “[(ngModel)]” directive to bind the properties of the field i.e. like #first_name=”ngModel”.

Besides storing the data, "ngModel" is responsible for providing the validation behavior (i.e. number, email, URL) and maintaining the control status (valid/invalid, touched/untouched, validation errors).

ngForm:

To trace out the form values and validation status the “ngForm” is used.

                                               

Image removed.

 

ngSubmit: 

 To get the values of the form while submitting use “ngSubmit”. This event gets called on form submission 

 

Image removed.

 

Validation:

Here, the validation is executed using the “required” attribute.

 

Image removed.

 

Once the form is submitted and if it is invalid then the error message gets displayed.

 Advantages and Disadvantages of Template-Driven Forms:

         - Handling the forms is so simple than reactive forms.
         - Template-driven form is also more enough to build a large range of forms
         - When we add more validator tags to a field then the form's readability drops and it becomes difficult for the web designers.
         - Unit Testing cannot be achieved with the form validations. The only way to test the logic is to run an end to end test with a browser FormControl

Reactive Forms

Practically, the form input values keep on changing over time. And so, the reactive forms provide a model-driven approach to handle these varying form input values. At a certain point, reactive forms provide access to the state and meaning of form control.  The component class or the component prototype used to controls the current state and value.

Basically a reactive form is an HTML form filed with RxJS to manage the status as a real-time stream. This makes a point clear that one can receive changes to the values as visible and respond to the changes accordingly with validation errors, feedback, database operations, etc.


Benefits of using Reactive forms in Angular:

Structured Data Flow:

As the reactive form is led by component class, soon after the creation of the link with FormControlDirective the form access directly to the FormControl. That's why all elements in the view(template) is connected to the FormControl(form model).

Since the reactive form is synchronous and it is not dependent on the UI rendering, whenever a change occurs and a view update is needed it will not re-render the DOM. Whereas in template-driven forms every specific form element is linked to a directive that manages the form model internally.

Immutability: 

Reactive forms perform as an immutable data structure, thus this form holds the data model pure. Whenever a change occurs to the form, the FormControl instance rather updating the existing data model it will return a new state (a new data model. This particular form uses observable operators to return a new data model by that it maintains the integrity of the model between changes. While in template-driven form, it uses the mutable approach by using ngModel.

Predictability:

Since the Reactive form is predictable it accesses the data model synchronously. The forms are created around measurable sources and the inputs and values are given as the sources of input values that can be accessed synchronously.  Also, they use observed streams to monitor form changes that predictability makes it easy to test.

Scalability:

The reactive element is synchronous that makes the scaling simple. Highly reusable greatly helps with large-scale forms.  While Template-driven form being asynchronous the scalability is tough.

FormControl
    
FormControl is a class that allows individual form control, monitors value, validation status, and gives a wide variety of public API methods. Like form input, checkbox, select, text area, etc.

A basic example of form control :

 

Image removed.

 

FormGroup

FormGroup is basically a group of instances of FormGroup that holds the track of the value and validation status of the related group, also it provides public APIs. Its a group of form fields that have the ability to manipulated and validated together.

 

Image removed.

 

Form Builder 

Form Builder helps in making things easy, it helps us to forget about all the newing form groups and form controls. 
FormBuilder replaces FormGroup and FormControls directly, it says as an alternate of both together.

Let’s see an example of it: 
 Firstly, import FormBuilder from @angular/forms and then to use the FormBuilder, request via dependency injection. And this is achieved through the constructor of our component.

Image removed.

 

 And,

 

Image removed.

                                          

Hence, the above case makes use of FormBuilder to create a new this.fb.group()  instead of using new FormGroup()

Extracting the Data from Form:

The values of the form can be accessed by its values property.

 

Image removed.

 

A developer needs to be more careful while doing this since the values are still referred by the form if one just copies that reference and modifies the data elsewhere the form will be impacted and this, in turn, causes weird side-effects.

Example in an onSubmit call of a form:

Snippet

 

Image removed.

 

Reset the Form by :

To reset the form, one needs to use the form's reset method without any parameter,

Snippet

 

Image removed.

 

which results in an empty object, or pass a set of default parameters along:

Snippet

 

Image removed.

 

How to use reactive forms in the Angular application?

To use reactive forms in the angular application developer need to import ReactiveFormsModule :

 

Snippet

Image removed.

 

 

With reactive forms, the logic is declared absolutely in the class of components, in app.component.html :

Snippet

 

Image removed.

 

formGroup:
In the component class, the form will be classified as a FormGroup, hence the formGroup directive allows the form group to be given a name.

formControlName:
Every form field should have a formControlName directive with a value which nothing but the name used in the component class.

ngSubmit:
nySubmit is the event that will be triggered upon submission of the form.

In app.component.ts let’s see how to define the  formGroup:

Snippet

 

Image removed.

 

Validation:

The validation process is simple, just by adding the validator class to the imports and declaring the form controls with arrays instead of simple string values. One can also notice how multiple validators are used in the same form of control by wrapping them into an array.
    
Here is an example:

Snippet

 

Image removed.

 

Conclusion:

Template Driven Forms are easy and have great power for form validation, it is the best fit for simple forms. But using Template Driven Form it is difficult to carry out the work in complex forms hence here the Reactive forms are used. Both forms have their own merits and demerits based on the utilization the form selection can be made. 

Also, read the article "Angular Components Interaction Methods - A Quick Study"

Article By,

Anni Joice

Associate Software Developer

Sandra Sadan

Associate Software Developer

Profile picture for user Web Team
Designation
Developer

Web Team

Developer