Web applications heavily rely on forms. In many ways Angular is so successful because two-way bindings and ng-model made creating dynamic forms easy.

Although very flexible, the AngularJS 1.x approach has some issues: the data flow in complex user interactions is hard to understand and debug.

Angular 2.x+ builds up on the ideas from AngularJS 1.x: it preserves the ease of creating dynamic forms, but avoids the issues making data flow hard to understand.

In this article we will look at how form handling (or input handling) works in Angular.

Read the Series

This is the seventh post in the Essential Angular series, which aims to be a short, but at the same time, fairly complete overview of the key aspects of Angular.

You can also check out the Essential Angular book, which has extra content not available on this blog.

Example App

Throughout this series I use the same application in the examples. This application is a list of tech talks that you can filter, watch, and rate.

You can find the source code of the application here.

Two Modules

In AngularJS 1.x, the ng-model directive was baked into the core framework. This is no longer the case. The @angular/core package doesn’t contain a form-handling library. It only provides the key primitives we can use to build one.

Of course, making everyone to build their own would not be practical. And that’s why the Angular team built the @angular/forms package with two modules: FormsModule and ReactiveFormsModule.

FormsModule implements AngularJS-style form handling. We create a form by placing directives in the template. We then use data bindings get data in and out of that form.

ReactiveFormsModule is another take on handling input, where we define a form in the component class and just bind it to elements in the template. We tend to use reactive programming to get data in and out of the form, hence the name “reactive”.

At first glance, these two modules seem very different. But once we understand the underlying mechanisms, we will see how much they have in common. In addition, it will give us an idea of how to build our own form-handling module if needed.

High-Level Overview

App Model

The app model is an object provided by the application developer. It can be a JSON object fetched from the server, or some object constructed on the client side. Angular doesn’t make any assumptions about it.

Form Model

The form model is a UI-independent representation of a form. It consists of three building blocks: FormControl, FormGroup, and FormArray. We will look at the form model in detail later in this chapter. Both FormsModule and ReactiveFormsModule use this model.

Form Directives

These are the directives connecting the form model to the DOM (e.g., NgModel). FormsModule and ReactiveFormsModule provide different sets of these directives.

DOM

These are ours inputs, checkboxes, and radio buttons.