Introduction to forms in Angular

Learn via video courses
Topics Covered

Angular offers two main approaches for handling user input: reactive and template-driven forms. While both methods facilitate capturing, validating, and updating user data, they have distinct characteristics. Reactive forms emphasize a more programmatic approach, leveraging observables and immutable data structures. In contrast, template-driven forms rely on directives and two-way data binding, simplifying template integration. Understanding these methodologies is crucial for determining the best fit for specific application needs. Both techniques streamline tasks such as user authentication, profile updates, and data validation. This guide elucidates the foundational components, nuances, and comparative aspects of these form strategies, aiding developers in making informed decisions for efficient web application development.

Prerequisites

This guide assumes you have a fundamental grasp of the following.

  1. HTML and TypeScript programming
  2. The principles of Angular app design, as defined in Angular Concepts
  3. The fundamentals of Angular template syntax

Angular Forms Module

This is the module that comes all together with angular core features and offers features that will aid in the development of basic and interactive applications.

@angular/forms

This module exports the necessary providers and directives for basic angular forms, making them available for import by NgModules that import it.

Types of Angular Forms

Angular supports two techniques to managing user input via forms:

  1. Template-driven
  2. Reactive

Template-Driven Approach

As the name implies, template-driven forms begin with a template and use data binding to get data to and from your components. It is template-first and allows you to direct your application's logic through your template.

Reactive Approach

To comprehend and begin developing forms in a reactive way, it is necessary to first define reactive programming. To oversimplify, reactive programming is the notion of building a program in such a manner that it essentially deals with and acts on asynchronous data streams.

You specify the whole tree of Angular form control classes in your component code and then tie them to native form control elements in your template with reactive forms. Because the component has access to both the form controls and the underpinning data model, it can push data model changes into the form control and vice versa, allowing it to react to changes in either direction.

Difference between Reactive Forms and Template-Driven Forms

Comparison onReactive FormsTemplate-driven Forms
Setup (form model)Reactive forms are more explicit. They are created in component class.Template-driven forms are less explicit. They are created by directives.
Data modelStructuredUnstructured
PredictabilitySynchronousAsynchronous
Form validationFunctionsDirectives
MutabilityImmutableMutable
ScalabilityLow-level API accessAbstraction on top of APIs

Building Blocks of Angular Forms

Form Control

The FormControl, which directly represents an individual form element in the template, is at the heart of any reactive form. As a result, any reactive form is nothing more than a collection of grouped FormControls.

We also assign starting values and validators at the FormControl level. As a result, everything we accomplished in the template using template-driven forms now occurs at the FormControl level in TypeScript code.

To summarise, FormControl is useful when we need to maintain the status and value of every specific form element, such as an input box or a checkbox.

Form Group

When we construct any shape, it rarely has only one element. We often wish to monitor a number of distinct fields and components under a single form or header.

In these circumstances, the FormGroup is beneficial for grouping relevant form fields into a single group. This allows us to choose whether to track the form controls individually or as a group.

For instance, we may obtain the complete form value or determine whether the form as a whole is legitimate (as a result of individual elements and their state).

Form Array

In Angular, the FormArray is a mechanism to handle a collection of Form Controls. A FormGroup, FormControl, or another FormArray can be used as controls.

In Angular forms, we may organise Form Controls in two ways. One users FormGroup, whereas the other users FormArray. The distinction is in how they carry it out. Controls in FormGroup become FormGroup properties. Each control is denoted by a key-value pair. The controls become part of an array when in FormArray.

It is easy to add controls dynamically in FormsArray because it is implemented as an Array.

Creating Your Form

Let's make a form with Angular forms:

Step1: Form Creation

Import FormsModule module:

Now, we'll start by creating an HTML template for our User Profile page.

Step2: Adding Angular Form Controls

As we have imported FormsModule and added form tag in the template, we are able to see few properties of form such as ng-untouched ng-pristine ng-valid.

Form controls are introduced to each input field by using the ngModel directive in the input tag.

Adding Angular Form Controls

Now, let's bind our form with ngSubmit method

user-profile.component.html

user-profile.component.ts

On Save click

Adding Angular Form Controls On Save click

Step3: Getting the JavaScript Object Representation

Another directive named NgForm is applied to a template variable to build the JavaScript Representation.

user-profile.component.html

user-profile.component.ts

On Save Click:

Getting the JavaScript Object Representation On Save click

Here we can examine the entire form object and use the many attributes that are accessible. The Ngform object is returned the form's JavaScript representation. Obtaining this representation simplifies form validation.

Step4: Angular Form Validation

Let's Add required in the firstname

user-profile.component.html

Now, when we will click on save button and check the console. We can see status:"INVALID" which will help us to handle error in the .ts file.

On Save Click

Form status INVALID


In the form object's controls, inside firstname, we would be able to see errors array - which will update us about error.

On Save click

Error Required


Let's add error message on the template

user-profile.component.html

On Save Click

Error Message

Conclusion

  • Forms in Angular help us to handle user inputs easily.
  • Angular framework comes up with two type of forms:
    • Template Driven
    • Reactive Form
  • Forms have three components
    • FormControl
    • FormGroup
    • FormArray
  • Forms make it easy to manage errors, which may be handled from both the template and the code.