Reactive forms and form validation with Angular

This article explains how to use Angular reactive forms. We’ll walk through how to set up a login form with form validation.

The setup is angular-cli app with @angular/cli@1.0.3, @angular@4.1.2 and @angular/material@2.0.0-beta.3.

Import module

First, we need to import the ReactiveFormsModule in app.module.ts.

Create the form in the controller

Then, let’s create the form in the controller in ngOnInit().

FormControl represents an input in the view. The first parameter is the default value and the second is a (or an array of) validator(s) for this field.

FormGroup is composed of a map taking as value an AbstractControl (which means either a FormControl, FormGroup or FormArray). We can nest our FormGroup if we want to create a complexe value. After the map, we can also add other validators at the form level if needed.

Note that we can access the form value by this.loginForm.value.

The validators can be default ones like Validators.required or a custom ones. It is just a function that returns a ValidatorFn, which means it takes an AbstractControl as a parameter (the field we are validating) and return a return code (the key) and some useful value (for the example the regexp).

Create the form in the view

Now that we have created the form, we’ll see how to render it. We use the Angular Material Design component to have a nice view, but the important thing is to add the formGroup attribute indicating our public form variable loginForm:

<form [formGroup]="loginForm">

as well as formControlName for each input that matches the map keys in loginForm:

<input type="email" mdInput formControlName="email" placeholder="Email" required>

To handle error messages, use:

  • loginForm.controls[‘<field_name>’].errors: to get error map for the field.
  • loginForm.controls[‘<field_name>’].pristine: to know whether the field is pristine.
  • loginForm.invalid: to check the global validity of the form.

As a whole:

Some style for a better rendering:

Thanks for reading my first article ;). You can find the full example on Github. Here is the link to the official documentation.

Another article to handle the form with async data.

Like what you read? Give Coralie Mycek a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.