Site icon Sails Software Inc

Reactive Forms in Angular

Reactive Forms in Angular

Nowadays most of the websites use the Forms to collect the user data and send it to the server for processing. Forms generally have text inputs, radio buttons, check boxes, buttons, etc to collect the different types of data from the user. In this blog we will briefly discuss:

Angular Forms

Angular provides 2 different approaches to handling user input through forms:

  1. Template-driven 
  2. Reactive or Model-driven

 

Template-driven forms:

Template-driven forms use the angular directives in the templates to handle the forms. In these forms we write logic, validations, controls, etc in template (HTML code). These are used for simple scenarios like a simple static form.

Reactive Forms:

In reactive forms we will create form programmatically means we create the instances of the form controls or form groups in typescript file. These are well suited for complex scenarios like dynamic form fields, custom validations, etc. 

The main form control properties which are very useful while implementing a form are:

Value: It will contain the data entered by the user.

Touched: This will be true if the user touches the input field.

Untouched: This property will be true if the user does not touch the input field.

Dirty: It will be true if the value is changed.

Pristine: It will be true if the value is not changed.

Valid: It will be true if the value is valid.

Errors: If the value is not valid, we can see the validation errors.

 

How to implement reactive form?

All the directives for building reactive forms are defined in a separate module called “ReactiveFormsModule”. So first we have to import this module into our app module as shown below.

Then we have to create a form like a signup form. When building reactive forms, we should create “FormControl” objects explicitly in the code. For that we need to import some classes like “FormGroup”, “FormControl” from @angular/forms.

FormControls are classes in Angular that can hold the data and the validation information of any form element. FormGroups are used to wrap a collection of FormControls.

FormGroup constructor has three parameters in which the last two are optional. 

“FormGroup (Controls: {[key: string]: AbstractControl ; },

Validator?: ValidatorFn,

AsyncValidator?: AsyncValidatorFn)” 

AbstractControl is the base class for FormControl and FormGroup. All properties that are common between these two classes are actually defined in the AbstractControl class.

After creating the FormControl objects we have to associate them with the template as shown below.

[formGroup] is a directive which is used to associate the form element with an actual FormGroup object that we created in our component. “formControlName” is another directive and we set this to the name of the key in our FormGroup object. formControlName and the key name in the object should be same.

Adding Validation 

We can assign one or more validators when creating FormControl objects. The constructor of the FormControl class will be like this:

“FormControl ( 

formState?: any, 

Validator?: ValidatorFn | ValidatornFn[], 

AsyncValidator?: AsyncValidatorFn | AsyncValidatorFn[])” 

In Angular we have a class called Validators in which all the built-in validators exist. These validators are methods defined in this class. We have methods called required, minLength(), maxLength(), Pattern() and email. By using this we can add validators to our form. We can also give multiple validators as an array.

Here for email, we have given required and email validators. For password we have given required and minLength validators which means that the field is mandatory and it should have minimum length 8 characters. Later we have to display some error messages in the template if the input field is not valid.

Here we have placed proper error messages when the FormControl is not valid. And we also disabled the Login button if the whole form is not valid.

Custom Validation

Instead of built-in validators we can also create our own custom validators. We define custom validators with functions. If we want to reuse the custom validator then we need to create a separate file. Otherwise, we can directly write that function inside our component file. The signature of the ValidatorFn looks like this:

“interface ValidationFn {

(c: AbstractControl): ValidatorErrors | null

}” 

The Validation function will take a parameter of type AbstractControl and it will return either validation errors or the null value.

For example, if I want to create a validator for the password field to avoid spaces. It is a good idea to create a separate file and implement a method inside that like shown below.

And in the component file we will add this validator to the password field.

Finally, in the template we have to display the error message for the password field.     

Form Input Upon Submit

We can call any method while we are submitting the form by binding the ngSubmit event to the method name in template. And we have to define that method inside the component.

Nested Form Groups

In simple forms like above we only have a single FormGroup. But, in a large application we might have a form with multiple subgroups. To implement this, we use this nested form groups concept. We can define one FormGroup inside another FormGroup as shown below.

To associate this FormGroup with the template we use a directive called “formGroupName”. As similar as formControlName directive, we will give the form group key name as the value of the formGroupName directive.

Example:

<div formGroupName=”account”>

FormArray

When we need to add the controls dynamically to the reactive forms, we can FormArray. It aggregates the values of each child FormControl into an array. Like FormGroup, the FormArray is also one of the ways to group the form controls. But, in FormGroup we represent controls as key-value pairs. In FormArray the controls become a part of an array which makes it easier to dynamically add the controls. To know more about the FormArray 

FormBuilder

In Angular we have a class called FormBuilder which we use to create reactive forms. It will provide cleaner code to create instances for FormControl, FormGroup and FormArray. This FormBuilder class has three methods (array, control, group) to create the instances. We need to import and inject this FormBuilder object into the constructor.

In the above example the form is created by using FormBuilder where the “name” is a FormControl and “contact” is a sub group of the form. “email” and “phone” are the FormControls of the sub group. And “topics” is the FormArray.

Summary

Written by

Nagaramya Gade

www.sailssoftware.com

 

 

Exit mobile version