Forms are probably the most crucial aspect of your web application. While we often get events from clicking on links or moving the mouse, it’s through forms where we get the majority of our rich data input from users.
On the surface, forms seem straightforward: you make an input tag, the user fills it out, and hits submit. How hard could it be?
It turns out, forms can be very complex. Here’s a few reasons why:
- Form inputs are meant to modify data, both on the page and the server
- Changes often need to be reflected elsewhere on the page
- Users have a lot of leeway in what they enter, so you need to validate values
- The UI needs to clearly state expectations and errors, if any
- Dependent fields can have complex logic
- We want to be able to test our forms, without relying on DOM selectors
Thankfully, Angular has tools to help with all of these things.
- FormControls encapsulate the inputs in our forms and give us objects to work with them
- Validators give us the ability to validate inputs, any way we'd like
- Observers let us watch our form for changes and respond accordingly
In this chapter we’re going to walk through building forms, step by step. We’ll start with some simple forms and build up to more complicated logic.
FormControls and FormGroups
The two fundamental objects in Angular forms are FormControl and FormGroup.
FormControl
A FormControl represents a single input field - it is the smallest unit of an Angular form.
FormControls encapsulate the field's value, and states such as being valid, dirty (changed), or has errors.
// create a new FormControl with the value “Nate”
let nameControl = new FormControl(“tarun”);
let name = nameControl.value; // -> tarun
// now we can query this control for certain values:
nameControl.errors // -> StringMap<string, any> of errors
nameControl.dirty // -> false
nameControl.valid // -> true
// etc.
For instance, here’s how we might use a FormControl in TypeScript:
To build up forms we create FormControls (and groups of FormControls) and then attach metadata and logic to them.
Like many things in Angular, we have a class (FormControl, in this case) that we attach to the DOM with an attribute (formControl, in this case). For instance, we might have the following in our form:
<! — part of some bigger form →
<input type=”text” [formControl]=”name” />
This will create a new FormControl object within the context of our form. We'll talk more about how that works below.
FormGroup
Most forms have more than one field, so we need a way to manage multiple FormControls. If we wanted to check the validity of our form, it's cumbersome to iterate over an array of FormControls and check each FormControl for validity. FormGroups solve this issue by providing a wrapper interface around a collection of FormControls.
let personInfo = new FormGroup({
firstName: new FormControl(“Nate”),
lastName: new FormControl(“Murray”),
zip: new FormControl(“90210”)
})
Here’s how you create a FormGroup:
FormGroup and FormControl have a common ancestor (AbstractControl). That means we can check the status or value of personInfo just as easily as a single FormControl:
personInfo.value; // -> {
// firstName: “Nate”,
// lastName: “Murray”,
// zip: “90210”
// }
// now we can query this control group for certain values, which have sensible
// values depending on the children FormControl's values:
personInfo.errors // -> StringMap<string, any> of errors
personInfo.dirty // -> false
personInfo.valid // -> true
// etc.
Notice that when we tried to get the value from the FormGroup we received an object with key-value pairs. This is a really handy way to get the full set of values from our form without having to iterate over each FormControl individually.
Our First Form
There are lots of moving pieces to create a form, and several important ones we haven’t touched on. Let’s jump in to a full example and I’ll explain each piece as we go along.
Here’s a screenshot of the very first form we’re going to build:
In our imaginary application we’re creating an e-commerce-type site where we’re listing products for sale. In this app we need to store the product’s name, so let’s create a simple form that takes the SKU as the only input field.
Let’s turn this form into a Component. If you recall, there are three parts to defining a component:
-
Configure the @Component() decorator
-
Create the template
-
Implement custom functionality in the component definition class
Let’s take these in turn:
Loading the FormsModule
In order to use the new forms library we need to first make sure we import the forms library in our NgModule.
There are two ways of using forms in Angular and we’ll talk about them both in this chapter: using FormsModule or using ReactiveFormsModule. Since we'll use both, we'll import them both into our module. To do this we do the following in our app.ts where we bootstrap the app:
import {
FormsModule,
ReactiveFormsModule
} from ‘[@angular/forms](http://twitter.com/angular/forms)’;
// farther down…
[@NgModule](http://twitter.com/NgModule)({
declarations: [
FormsDemoApp,
DemoFormSkuComponent,
// … our declarations here
],
imports: [
BrowserModule,
FormsModule, // ← add this
ReactiveFormsModule // ← and this
],
bootstrap: [ FormsDemoApp ]
})
class FormsDemoAppModule {}
This ensures that we’re able to use the form directives in our views. At the risk of jumping ahead, the FormsModule gives us template driven directives such as:
-
ngModel and
-
NgForm
Whereas ReactiveFormsModule gives us directives like
-
formControl and
-
ngFormGroup
… and several more. We haven’t talked about how to use these directives or what they do, but we will shortly. For now, just know that by importing FormsModule and ReactiveFormsModule into our NgModule means we can use any of the directives in that list in our view template or inject any of their respective providers into our components.
Simple Form: @Component Decorator
Now we can start creating our component:
import { Component, OnInit } from ‘[@angular/core](http://twitter.com/angular/core)’;
[@Component](http://twitter.com/Component)({
selector: ‘app-demo-form’,
templateUrl: ‘./demo-form.component.html’
})
class AppDemoComponent(){}
Here we define a selector of app-demo-form. If you recall, selector tells Angular what elements this component will bind to. In this case we can use this component by having a app-demo-form tag like so:
<app-demo-form></app-demo-form>
Simple Form: template
Let’s look at our template:
<div class=”ui raised segment”>
<h2 class=”ui header”>Demo Form: </h2>
<form #f=”ngForm”
(ngSubmit)=”onSubmit(f.value)”
class=”ui form”>
<div class=”field”>
<label for=”Input”></label>
<input type=”text”
id=”Input”
placeholder=””
name=”” ngModel>
</div>
<button type=”submit” class=”ui button”>Submit</button>
</form>
</div>
form & NgForm
Now things get interesting: because we imported FormsModule, that makes NgForm available to our view. Remember that whenever we make directives available to our view, they will get attached to any element that matches their selector.
NgForm does something handy but non-obvious: it includes the form tag in its selector (instead of requiring you to explicitly add ngForm as an attribute). What this means is that if you import FormsModule, NgForm will get automaticallyattached to any