How to do Conditional Validation on valueChanges method in Angular Reactive Forms

Read full article on the Infragistics blog

In this blog post, we will learn to use Angular Reactive Forms value change detection and enable conditional validation on basis of that.

Learn How to Create Your First Angular Reactive Form here

Let us say you have a Reactive Form created using FormBuilder class as shown below:

You have created loginForm, which has three controls: email, password, and phonenumber. Here, you are using FormBuilder to create a reactive form. On the component template, you can attach loginForm as shown in the code listing below. Using property binding, the formGroup property of the HTML form element is set to loginForm and the formControlName value of these controls are set to the individual FormControl property of FormBuilder.

We have also put error messages for email and phone number fields. Besides, that submit button would only be enabled when the form is valid.  Form submit is handled as shown in the listing below:

If the form is valid in browser console, you will get the output as below:

In addition, if there is an error, submit button would be disabled and an error message will be shown as below:

You can learn to create Custom Validators for Angular Reactive Forms here

Now assume a scenario that you have a radio button to send a notification. The user should able to select the send notification option, and on basis of that, certain FormControl will have some validation.

Consider the form below,

We have added a Send Notification option. If the user selects Phone to send notification then Phone Number field should be required, otherwise, it should not be. To achieve this we need to perform following tasks,

  1. Listening to changes
  2. Put conditional validation

To start with, let us modify our form to handle the notification. So now form has a notification FormControl with the default value set to null as shown in the listing below :

On the Reactive form template, we will add radio button group to handle Send Notification option.

Continue Reading full article on the Infragistics blog here

How to create Custom Validator for Angular Reactive Forms

Learn full article on the Infragistics blog

In this blog post, we will learn to create custom validators in Angular Reactive Forms. If you are new to reactive forms, learn how to create your first Angular reactive form here.

Let’s say we have a login form as shown in the listing below. Currently, the form controls do not have any validations attached to it.

Here, we are using FormGroup to create a reactive form. On the component template, you can attach loginForm as shown in the code listing below. Using property binding, the formGroup property of the HTML form element is set to loginForm and the formControlName value of these controls are set to the individual FormControl property of FormGroup.

This will give you a reactive form in your application:

image

Using Validators

Angular provides us many useful validators, including required, minLength, maxLength, and pattern. These validators are part of the Validators class, which comes with the @angular/forms package.

Let’s assume you want to add a required validation to the email control and a maxLength validation to the password control. Here’s how you do that:

To work with Validators, make sure to import them in the component class:

On the template, you can use validators to show or hide an error message. Essentially, you are reading the formControl using the get() method and checking whether it has an error or not using the hasError() method. You are also checking whether the formControl is touched or not using the touched property.

If the user does not enter an email, then the reactive form will show an error as follows:

image

Custom Validator

Let us say you want the age range to be from 18 to 45. Angular does not provide us range validation; therefore, we will have to write a custom validator for this.

In Angular, creating a custom validator is as simple as creating another function. The only thing you need to keep in mind is that it takes one input parameter of type AbstractControl and it returns an object of key value pair if the validation fails.

Let’s create a custom validator called ageRangeValidator, where the user should able to enter an age only if it’s in a given range.

image

The type of the first parameter is AbstractControl because it is a base class of FormControl, FormArray, and FormGroup, and it allows you to read the value of the control passed to the custom validator function. The custom validator returns either of the following:

1. If the validation fails, it returns an object, which contains a key value pair. Key is the name of the error and the value is always Boolean true.

2. If the validation does not fail, it returns null.

Learn full article on the Infragistics blog

How to Create Your First Angular Reactive Form

Read full article on the Infragistics blog

Out of the box, Angular provides us with two types of forms:

  1. Template Driven Forms
  2. Reactive Forms

In Template Driven Forms, you create controls on the component template and bind data using ngModel. With these, you do not create controls, form objects, or write code to work with pushing and pulling of data between component class and template; Angular does all of these tasks for you. In template driven forms, there is very little code for validations in the component class, and they’re asynchronous.

In Reactive Forms, you create form controls as trees of objects in the component class and bind them to the native form controls in the template. All validations and the creation of form controls are written in the component class. In Reactive Forms, all validations and changes in the state of native forms are synchronous, so you can write code in the component class to observe them.  You should choose to create reactive forms when the data model is immutable and usually mapped to a database.

The major difference between these two approaches of creating forms? In reactive forms you do not use directives such as ngModel, required, etc. You create all controls and their validations in the component class. Reactive forms are easy to test and maintain, so in this post we will learn to create a basic Reactive Form, using FormControl, FormGroup, FormBuilder class, and adding validations.

Step 1: Add Reactive Forms Module

To start working with reactive forms, first add ReactiveFormsModle in the App Module as shown in the next listing:

Step 2: Import required module in Component

Next, you need to import the required Reactive forms classes such as FormGroup, FormControl, FormArray in the components class. We will use these classes to construct our reactive form.  After importing these classes, the component class should look like the listing below:

Your component class can be different from the AppComponent created above depending on your implementation; however, here we have imported FormGroup, FormControl, and FormArray classes. Let’s learn about these classes one by one:

Step 3: Using the FormControl class

The FormControl class corresponds to one individual form control, tracking its value and validity. While creating your reactive form, you will create an object of the FormControl class. The FormControl constructor takes three parameters:

  1. Initial data value, which can be null.
  2. Array of synchronous validators. This is an optional parameter.
  3. Array of asynchronous validators. This is an optional parameter.

In the component class, you can create a FormControl as shown in the listing below:

We are not passing any optional parameters like sync validations or async validations, but we will explore these parameters while adding validation to a FormControl.

On the View, you can use email FormControl as shown below:

As you see, we are using property binding to bind the formControl email to the input element on the view.

Read full article on the Infragistics blog