Software systems to innovate and grow

How to Handle Angular Reactive Forms

By Engineering Team November 19, 2018 10 mins read

Presenting the developer with a model-driven approach to handle form fields, plan to dive deep into Angular reactive forms. Discover the details as we walk you through a code example and show you how to create and update simple form control, use multiple controls in a group and validate form values with reactive forms in the angular framework. Let’s start by shedding light on the two types of forms Angular provides.

Introduction to Angular Forms

There are two main types of code, template driven and code driven. The template-driven method requires you to write your form using only directives in your template. Code-driven or model-driven, or the reactive way is when you write a description of the form in your component. It uses directives to bind the form to the inputs, textareas and selects in your template. Let’s compare the main principles of each.

Template-driven

  • Shines for simple forms with not much validation
  • Provides a way to create sophisticated forms while writing as little JavaScript as possible
  • Similar to the AngularJS forms, where the directives and behaviours are bound to our templates and Angular does the rest
  • Bind directives and behaviour to our templates using ngModel and perhaps required, minlength and so forth
  • Implicit creation of FormControl() by directives
  • Source of truth: template
  • Async

Code-driven or Model-driven

  • More verbose, but also more powerful
  • Enables us to test forms without relying on end-to-end tests
  • Avoid directives such as ngModel, required and others
  • Explicit creation of FormControl()
  • Source of truth: component class
  • Sync

Reactive Form Fundamentals

One interesting feature about reactive forms is that instead of defining the form in your template, the form structure is defined in JavaScript code. With just a few lines of code, the Angular ReactiveFormsModule enables you to solve input-handling problems in an elegant way. The reactive forms make use of an explicit and immutable approach to manage the state of a form at a given point in time. The main idea behind it is that each change to the form state returns a new state. As a result, the integrity of the model is maintained between changes.

Reactive forms make use of reactive programming and are built around observable streams. Form fields are provided as streams of input values while giving you synchronous access to the data. This approach allows your templates to take advantage of these streams of form state changes, rather than being dependent on them. The same streams are available to consumers outside your templates so they can manipulate that data in a safe way. Testing is easier with reactive forms because your form data changes are now predictable. This is able to happen because you can be certain that your data will have consistent results when requested.

Register User Form Example

Presented as a simple register user form, here is an example made using Angular Reactive forms. To use reactive forms, you need to import the ReactiveFormsModule into the parent module. In this case the AppModule.

Defining the User Model

With the Reactive forms approach you create your own JavaScript models instantiated inside a component class that renders the form rather than binding object models to directives like it’s done with template-driven forms. This is a basic example so the model will only have a username, email and password.

Containing the Form With Components

In this basic example, the user will learn to submit the form only if it has no errors. This means the Register button will be disabled if errors are found using reactive errors. The user component has the form logic provided by the form builder and the validators.

Defining the Form Elements

With reactive forms, you need to create a form model that represents the DOM structure in our component. For this, you have the low-level APIs for FormGroup and FormControl.
FormControl represents a form field and FormGroup a set of FormControls.

FormBuilder

In this example, the user form is created by the FormBuilder. FormBuilder it’s essentially a module that creates FormGroup, FormControl and FormArray instances for you so you don’t have to declare each one of them in your form definition. Basically, it reduces the boilerplate.

Validators

All the validations on the form are done with Validators from angular/forms. All the fields are required, so they are validated with Validators.required. The email and password inputs should match a special pattern, they are validated with Validators.pattern for pattern validation using a regex. You can see the definitions in the component and the different errors being shown in the template.

Template file: user-form.component.html

Component file: user-form.component.ts

Wrapping Everything Up

Now it’s time to include everything in the parent module (app.module in this case) in order to run the app.

The app.module.ts file will end up looking like this:

You should now have a better understanding of the reactive forms approach to Angular forms. On the reactive side, you have the ability to access instant sharing form control, forms group, and forms array as needed. In these, you are directly manipulating the forms in the component class. They require an investment upfront, and sometimes this means more boilerplate. The results are explicit. Without constraints on the template, reactive forms are predictable and everything behaves synchronously. Both Angular form approaches are worthy methods. Based on your code style and preferences, it is up to you which one to choose for your applications.