Reader small image

You're reading from  Expert Angular

Product typeBook
Published inJul 2017
Reading LevelExpert
PublisherPackt
ISBN-139781785880230
Edition1st Edition
Languages
Right arrow
Author (1)
Sridhar Rao Chivukula
Sridhar Rao Chivukula
author image
Sridhar Rao Chivukula

Sridhar Rao Chivukula is a technical lead at Mindtree Ltd and is based out of New York City. He brings with him more than a decade of rich hands-on experience in all aspects of frontend engineering. He has worked with leading companies such as Oracle, Tech Mahindra, and Cognizant Technology Solutions. He has a Bachelor's degree in Information Technology. He is the author of the books Expert Angular and PHP and Web 2.0 Application Interfaces, published by Packt.
Read more about Sridhar Rao Chivukula

Right arrow

Advanced Forms in Angular

In Chapter 7, Asynchronous Programming Using Observables, we used Observables to build a simple, yet easily extendable JSON API to query the Marvel Cinematic Universe. In this chapter, we will build the forms that will allow us to query our API in a more user-friendly way. These forms will help us to not only retrieve movies from the Marvel Cinematic Universe, but also to add movies. In addition to the forms themselves, we will obviously need to build on our API, so it supports the addition and modification of movies.

In this chapter, we will see the following topics covered in detail:

  • Reactive forms
  • Control and ControlGroup
  • Form directive
  • Using FormBuilder
  • Adding validations
  • Custom validation

Getting started

As stated in the introduction of this chapter, we will build upon our JSON API for the Marvel Cinematic Universe of Chapter 7, Asynchronous Programming Using Observables. To be a bit more precise, we will improve the Promise-based version. Why Promises instead of pure observers? Well, Promises are an extremely powerful tool, and they are used in the majority of Angular/Typescript projects I have seen so far. Consequently, a bit more practice with Promises won't hurt much.

You can find the code of the Promises part here http://bit.ly/mastering-angular2-chap7-part3.

To clone this code into a new repo called advanced-forms, use the following command:

$ git clone --depth one https://github.com/MathieuNls/mastering-
angular2 advanced-forms
$ cd advanced-forms
$ git filter-branch --prune-empty --subdirectory-filter chap7/angular-
promise HEAD
$ npm install

These...

Reactive forms

In Chapter 8, Template and Data Binding Syntax, we learned how to leverage Data Binding and templating in Angular. Here, we'll combine these new notions with forms. Anyone with two hours, of HTML experience knows what <form> means and how to use them. With a couple of hours of HTML behind you, you know how to identify the different information in your forms and choose a method (that is GET, POST, PUT, and DELETE) to send everything to the backend of your choice.

In this recipe, however, we will build forms using imperative TypeScript code instead of good old HTML. Why, you ask? Well, this allows us to test our forms without relying on end-to-end tests that need the DOM to be generated. With reactive forms, we can test our form with classical unit tests as described in Chapter 16, Testing Angular Apps Using Jasmine and Protractor Frameworks.

Let...

Using FormBuilder

FormBuilder is an injectable helper class of the @angular/forms package of Angular. This class helps to reduce the wordiness of form creation as demonstrated in the following code:

this.movieForm = this.formBuilder.group({
movie_id: '',
title: '',
phase: '',
category_name: '',
release_year: '',
running_time: '',
rating_name: '',
disc_format_name: '',
number_discs: '',
viewing_format_name: '',
aspect_ratio_name: '',
status: '',
release_date: '',
budget: '',
gross: '',
time_stamp: ''
});

As you can see, using the group method of the FormBuilder class, the declaration of FormGroup and FormControl is now implicit. We only need to have the field name followed by its default...

Adding validations

Dealing with forms is often a pain for developers because you obviously can't trust the inputs provided by the user. It is either because they are just not paying attention to what you expect in your forms or because they want to break things. Validating inputs incoming from a form is painful in every language, both server and client-side.

Now, the Angular team came up with a rather simple way to validate inputs by defining what is expected from each field right at the form's creation using Validators. Angular contains the following built-in Validators that we can use:

  • required: Requires a non-empty value
  • minLength(minLength: number): Requires the control value to have a minimum length of minLength
  • maxLength(maxLength: number): Requires the control value to have a maximum length of maxLength
  • pattern(pattern: string): Requires that the control value...

Custom validation

In the previous section, we saw how to use validators and combine validators together to create more complex validation. The Validators.required, Validators.minLength, Validators.maxLength, and Validators.pattern combinations can cover a lot of validation cases that can arise during the development of your Angular application. If the time comes where you can't handle your validation needs with the built-in validator, then you can build your very own validator.

In this section, we'll see how to validate that the movie_id field contains a valid entry (that is a number that is between one and four digits long) and that another movie does not already use the id. To do so, we can create the following class:


import { FormControl } from '@angular/forms';

interface ValidationResult {
[key:string]:boolean;
}

export class MovieIDValidator{
static idNotTaken...

Two-way Data Binding with ngModel

A very convenient process when creating or updating the model of your Angular application through forms is Two-way Data Binding with ngModel. In the previous application, we had the following submit() method:

private submit(){
console.log(
"Form Values",
this.movieForm.value.movie_id,
this.movieForm.value.title,
this.movieForm.value.phase,
this.movieForm.value.category_name,
this.movieForm.value.release_year,
this.movieForm.value.running_time,
this.movieForm.value.rating_name,
this.movieForm.value.disc_format_name,
this.movieForm.value.number_discs,
this.movieForm.value.viewing_format_name,
this.movieForm.value.aspect_ratio_name,
this.movieForm.value.status,
this.movieForm.value.release_date,
this.movieForm.value.budget,
this.movieForm.value.gross,
this.movieForm.value.time_stamp
...

Keeping things neat (extra credit)

I have always found that forms are the bane of clean, neat, organized HTML templates. Even small forms, well indented and separated by comments, look cluttered to my eyes. To solve this problem in an Angular way, we can create directives that keep forms input organized. Here's an example of what I use when creating a form for Toolwatch.io:

<toolwatch-input 
[id] = "'email'"
[control] = "loginForm.controls.email"
[errorLabel] = "'email-required'"
[submitAttempt] = "submitAttempt"
[autoCapitalize] = false
[autoCorrect] = false
[spellCheck] = false
>

As you can see, the directive accepts a different @Input parameter that controls how the input will look and behave.

Here's the related component:

import {...

Summary

In this chapter, we learned how to take advantages of reactive forms. Reactive forms can be created manually or programmatically using FormBuilder. Moreover, we tackled the reactive part of reactive forms by emphasizing the relationship between your HTML models and your ngModel, so every change on a given form is propagated to the model. We also saw how to customize validations and embed our newly acquired knowledge about forms in clean, reusable directives.

In the next chapter, we will learn how to integrate material design with Angular in order to create dashing and responsive applications.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Expert Angular
Published in: Jul 2017Publisher: PacktISBN-13: 9781785880230
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Sridhar Rao Chivukula

Sridhar Rao Chivukula is a technical lead at Mindtree Ltd and is based out of New York City. He brings with him more than a decade of rich hands-on experience in all aspects of frontend engineering. He has worked with leading companies such as Oracle, Tech Mahindra, and Cognizant Technology Solutions. He has a Bachelor's degree in Information Technology. He is the author of the books Expert Angular and PHP and Web 2.0 Application Interfaces, published by Packt.
Read more about Sridhar Rao Chivukula