Advertisement
  1. Code
  2. Angular
Code

Introduction to Forms in Angular 4: Reactive Forms

by
Difficulty:BeginnerLength:LongLanguages:
This post is part of a series called Introduction to Forms in Angular 4.
Introduction to Forms in Angular 4: Template-Driven Forms
Introduction to Forms in Angular 4: Writing Custom Form Validators
Final product image
What You'll Be Creating

This is the second part of the series on Introduction to Forms in Angular 4. In the first part, we created a form using the template-driven approach. We used directives such as ngModel, ngModelGroup and ngForm to supercharge the form elements. In this tutorial, we will be taking a different approach to building forms—the reactive way. 

Reactive Forms

Reactive forms take a different approach compared to that of the template-driven forms. Here, we create and initialize the form control objects in our component class. They are intermediate objects that hold the state of the form. We will then bind them to the form control elements in the template.

The form control object listens to any change in the input control values, and they are immediately reflected in the object's state. Since the component has direct access to the data model structure, all changes can be synchronized between the data model, the form control object, and the input control values. 

High level overview of Reactive forms using model-driven approach

Practically speaking, if we are building a form for updating the user profile, the data model is the user object retrieved from the server. By convention, this is often stored inside the component's user property (this.user). The form control object or the form model will be bound to the template's actual form control elements.

Both these models should have similar structures, even if they are not identical. However, the input values shouldn't flow into the data model directly. The image describes how the user input from the template makes its way to the form model.

Let's get started.

Prerequisites

You don’t need to have followed part one of this series, for part two to make sense. However, if you are new to forms in Angular, I would highly recommend going through the template-driven strategy. The code for this project is available on my GitHub repository. Make sure that you are on the right branch and then download the zip or, alternatively, clone the repo to see the form in action. 

If you prefer to start from scratch instead, make sure that you have Angular CLI installed. Use the ng command to generate a new project. 

Next, generate a new component for the SignupForm or create one manually. 

Replace the contents of app.component.html with this:

Here is the directory structure for the src/ directory. I've removed some non-essential files to keep things simple.

As you can see, a directory for the SignupForm component has been created automatically. That's where most of our code will go. I've also created a new User.ts for storing our User model.

The HTML Template

Before we dive into the actual component template, we need to have an abstract idea of what we are building. So here is the form structure that I have in my mind. The signup form will have several input fields, a select element, and a checkbox element. 

The HTML Template

Here is the HTML template that we will be using for our registration page. 

HTML Template

The CSS classes used in the HTML template are part of the Bootstrap library used for making things pretty. Since this is a not a design tutorial, I won't be talking much about the CSS aspects of the form unless necessary. 

Basic Form Setup

To create a Reactive form, you need to import  the ReactiveFormsModule from @angular/forms and add it to the imports array in app.module.ts.

app/app.module.ts

Next, create a User model for the registration form. We can either use a class or an interface for creating the model. For this tutorial, I am going to export a class with the following properties.

app/User.ts

Now, create an instance of the User model in the SignupForm component. 

app/signup-form/signup-form.component.ts

For the signup-form.component.html file, I am going to use the same HTML template discussed above, but with minor changes. The signup form has a select field with a list of options. Although that works, we will do it the Angular way by looping through the list using the ngFor directive.

app/signup-form/signup-form.component.html

Note: You might get an error that says No provider for ControlContainer. The error appears when a component has a <form> tag without a formGroup directive. The error will disappear once we add a FormGroup directive later in the tutorial.

We have a component, a model, and a form template at hand. What now? It's time to get our hands dirty and become acquainted with the APIs that you need to create reactive forms. This includes FormControl and FormGroup

Tracking the State Using FormControl

While building forms with the reactive forms strategy, you won't come across the ngModel and ngForm directives. Instead, we use the underlying FormControl and FormGroup API.

A FormControl is a directive used to create a FormControl instance that you can use to keep track of a particular form element's state and its validation status. This is how FormControl works:

email is now a FormControl instance, and you can bind it to an input control element in your template as follows:

The template form element is now bound to the FormControl instance in the component. What that means is any change to the input control value gets reflected at the other end. 

A FormControl constructor accepts three arguments—an initial value, an array of sync validators, and an array of async validators—and as you might have guessed, they are all optional. We will be covering the first two arguments here. 

Angular has a limited set of built-in validators. The popular validator methods include Validators.required, Validators.minLength, Validators.maxlength, and Validators.pattern. However, to use them, you have to import the Validator API first.

For our signup form, we have multiple input control fields (for email and password), a selector field, and a checkbox field. Rather than creating individual FormControl objects, wouldn't it make more sense to group all these FormControls under a single entity? This is beneficial because we can now track the value and the validity of all the sub-FormControl objects in one place. That's what FormGroup is for. So we will register a parent FormGroup with multiple child FormControls. 

Group Multiple FormControls With FormGroup

To add a FormGroup, import it first. Next, declare signupForm as a class property and initialize it as follows:

app/signup-form/signup-form.component.ts

Bind the FormGroup model to the DOM as follows: 

app/signup-form/signup-form.component.html

[formGroup] = "signupForm" tells Angular that you want to associate this form with the FormGroup declared in the component class. When Angular sees formControlName="email", it checks for an instance of FormControl with the key value email inside the parent FormGroup. 

Similarly, update the other form elements by adding a formControlName="value" attribute as we just did here.

To see if everything is working as expected, add the following after the form tag:

app/signup-form/signup-form.component.html

Pipe the SignupForm property through the JsonPipe to render the model as JSON in the browser. This is helpful for debugging and logging. You should see a JSON output like this.

Form state and validty in Model-driven forms

There are two things to note here:

  1. The JSON doesn't exactly match the structure of the user model that we created earlier. 
  2. The signupForm.status displays that the status of the form is INVALID. This clearly shows that the Validators.required on the email control field is working as expected. 

The structure of the form model and the data model should match. 

To get the hierarchical structure of the data model, we should use a nested FormGroup. Additionally, it's always a good idea to have related form elements under a single FormGroup. 

Nested FormGroup

Create a new FormGroup for the password.

app/signup-form/signup-form.component.ts

Now, to bind the new form model with the DOM, make the following changes:

app/signup-form/signup-form.component.html

formGroupName = "password" performs the binding for the nested FormGroup. Now, the structure of the form model matches our requirements.

Next up, we need to validate the form controls.

Validating the Form

We have a simple validation in place for the email input control. However, that's not sufficient. Here is the entire list of our requirements for the validation.

  • All form control elements are required.
  • Disable the submit button until the status of the form is VALID.
  • The email field should strictly contain an email id.
  • The password field should have a minimum length of 8.
Validating the form

The first one is easy. Add Validator.required to all the FormControls in the form model. 

app/signup-form/signup-form.component.ts 

Next, disable the button while the form is INVALID.

app/signup-form/signup-form.component.html

To add a constraint on email, you can either use the default Validators.email or create a custom Validators.pattern() that specifies regular expressions like the one below:

Use the minLength validator for the password fields.

That's it for the validation. However, the form model logic appears cluttered and repetitive. Let's clean that up first. 

Refactoring the Code Using FormBuilder

Angular provides you with a syntax sugar for creating new instances of FormGroup and FormControl called FormBuilder. The FormBuilder API doesn't do anything special other than what we've covered here.

It simplifies our code and makes the process of building a form easy on the eyes. To create a FormBuilder, you have to import it into signup-form.component.ts and inject the FormBuilder into the constructor.

app/signup-form/signup-form.component.ts 

Instead of a creating a new FormGroup(), we are using this.fb.group to build a form. Except for the syntax, everything else remains the same.

app/signup-form/signup-form.component.ts 

Displaying Validation Errors 

For displaying the errors, I am going to use the conditional directive ngIf on a div element. Let's start with the input control field for email:

There are a couple of issues here. 

  1. Where did invalid and pristine come from? 
  2. signupForm.controls.email.invalid is too long and deep.
  3. The error doesn't explicitly say why it's invalid.

To answer the first question, each FormControl has certain properties like invalid, valid, pristine, dirty, touched, and untouched. We can use these to determine whether an error message or a warning should be displayed or not. The image below describes each of those properties in detail.

 FormControl Properties in Angular Reactive approach

So the div element with the *ngIf will be rendered only if the email is invalid. However, the user will be greeted with errors about the input fields being blank even before they have a chance to edit the form. 

To avoid this scenario, we've added the second condition. The error will be displayed only after the control has been visited.

To get rid of the long chain of method names (signupForm.controls.email.invalid), I am going to add a couple of shorthand getter methods. This keeps them more accessible and short. 

app/signup-form/signup-form.component.ts 

To make the error more explicit, I've added nested ngIf conditions below:

app/signup-form/signup-form.component.html

We use email.errors to check all possible validation errors and then display them back to the user in the form of custom messages. Now, follow the same procedure for the other form elements. Here is how I've coded the validation for the passwords and the terms input control.

app/signup-form/signup-form.component.html

Submit the Form Using ngSubmit

We are nearly done with the form. It lacks the submit functionality, which we are about to implement now.

On form submit, the form model values should flow into the component's user property.

app/signup-form/signup-form.component.ts

Wrapping It Up

If you've been following this tutorial series from the start, we had a hands-on experience with two popular form building technologies in Angular. The template-driven and model-driven techniques are two ways of achieving the same thing. Personally, I prefer to use the reactive forms for the following reasons:

  • All the form validation logic will be located in a single place—inside your component class. This is way more productive than the template approach, where the ngModel directives are scattered across the template.
  • Unlike template-driven forms, Model-driven forms are easier to test. You don't have to resort to end-to-end testing libraries to test your form.
  • Validation logic will go inside the component class and not in the template.
  • For a form with a large number of form elements, this approach has something called FormBuilder to make the creation of FormControl objects easier.

We missed out on one thing, and that is writing a validator for the password mismatch. In the final part of the series, we will cover everything you need to know about creating custom validator functions in Angular. Stay tuned until then.

In the meantime, there are plenty of frameworks and libraries to keep you busy, with lots of items on Envato Market to read, study, and use.

Advertisement
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.