Angular Forms and Validations

Shailendra Chauhan  Print 
Posted On : 30 Jul 2018
Updated On : 15 Aug 2018
Total Views : 217

Forms are the mandatory building blocks of a web application. You use forms for various activities like user login or signup, book a flight, place an order etc.

In this article, you will learn about different ways of creating forms in Angular. Angular provides two ways to create forms – Template Driven and Model Driven.

Types of Angular Forms

Angular Form Building Blocks

The basic building blocks of an Angular form are : FormsGroup, FormControl, FormArray and Validations.

Angular Form Building Blocks

Angular Form and Form Controls States

Angular Forms and it's controls do change in it's states as user starts interaction with the form input controls. This state transition is helpful to get the information about the form and it's input control state. Based upon the get information you can show or hide error messages and even you can check the validity of the form.

Angular Form and Form Controls States

States Transition

  1. untouched => touched

  2. invalid => valid

  3. pristine => dirty

Angular Form Validations

Angular Form Validations are based on HTML5 validations. Angular Form Validations validate the user input for accuracy and completeness. All validations are performed on client-side.

Angular Forms Built-In Validation

  1. required

  2. minlength

  3. maxlength

  4. pattern

  5. email – supports in Ng4

  6. min

  7. max

Template Driven Form

Template-driven Form is setup and configured in HTML Code. Template-driven Form is easy to use and suits for simple form. Template-driven Form uses directives (ngForm, ngModel) and reference name(#refName) for creating forms.

Template Driven Form

Model Driven Form

Model-driven form is setup and configured in component class. It is based on reactive style of programming where you use the underlying APIs FormControl and FormGroup that track the value and validation status. Reactive forms offer the ease of testing, and validation.

Model Driven Form

Template Driven vs. Model Driven Form

Template Driven
Model Driven Form
Form is setup and configured in HTML Code
Form is setup and configured in component class using FormBuilder
Easy and suits for simple form
Flexible and suits for complex form
Two-way data binding
No data binding(immutable data model)
Automatically track form and input element state
Reactive Transformation that can react to changes in data across the app
Form is passed to component class via ngSubmit()
Form can be accessed in component class without passing it via ngSubmit()
Unit Testing is complex
Unit Testing is easy
What do you think?

I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.

Courses
Free Interview Books
 
+