Angular Reactive Forms With Validation šŸ‘‡

Nirmal Kumar
YavarTechWorks
Published in
4 min readSep 26, 2022

Reactive Forms

Reactive forms provide a model-driven approach to handling form inputs whose values change over time. This guide shows you how to create and update a basic form control, progress to using multiple controls in a group, validate form values and create dynamic forms where you can add or remove controls at run time.

import { ReactiveFormsModule } from '@angular/forms';@NgModule({imports: [// other imports ...ReactiveFormsModule],})

Overview of reactive forms

Reactive forms use an explicit and immutable approach to managing a formā€™s state at a given time. Each change to the form state returns a new state, which maintains the integrity of the model between changes. Reactive forms are built around observable streams, where form inputs and values are provided as streams of input values, which can be accessed synchronously.

Reactive forms also provide a straightforward path to testing because you are assured that your data is consistent and predictable when requested. Any consumers of the streams have access to manipulate that data safely.

Reactive forms differ from template-driven forms in distinct ways. Reactive forms provide synchronous access to the data model, immutability with observable operators, and change tracking through observable streams.

Template-driven forms let direct access to modify data in your template but are less explicit than reactive forms because they rely on directives embedded in the template and mutable data to track changes asynchronously. See the Forms Overview for detailed comparisons between the two paradigms.

Form Validation

Form validation is used to ensure that user input is complete and correct. This section covers adding a single validator to a form control and displaying the overall form status. Form validation is covered more extensively in the Form Validation guide.

Use the following steps to add form validation.

  1. Import a validator function in your form component.

2. Add the validator to the field in the form.

3. Add logic to handle the validation status.

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

CLASSES:

AbstractControl:

The abstract base class for the concrete form control classes FormControl, FormGroup, and FormArray. It provides their common behaviors and properties.

FormControl

Manages the value and validity status of an individual form control. It corresponds to an HTML form control such as <input> or <select>.

FormGroup

Manages the value and validity state of a group of AbstractControl instances. The groupā€™s properties include its child controls. The top-level form in your component is FormGroup.

FormArray

Manages the value and validity state of a numerically indexed array of AbstractControl instances.

FormBuilder

An injectable service that provides factory methods for creating control instances.

DIRECTIVES:

FormControlDirective

Syncs a standalone FormControl instance to a form control element.

FormControlName

Syncs FormControl in an existing FormGroup instance to a form control element by name.

FormGroupDirective

Syncs an existing FormGroup instance to a DOM element.

FormGroupName

Syncs a nested FormGroup instance to a DOM element.

FormArrayName

Syncs a nested FormArray instance to a DOM element.

Built-in validators

ā­•Required Validator

ā­•Minlength Validator

ā­•Maxlength Validator

ā­•Pattern Validator

ā­•Email Validator

ā­•Min

ā­•Max

ā­•Compose

ā­•Null validator

ā­•Required true

ā­•Compose Async

Required Validator

The required validator is a sync validator, which returns true only if the formcontrol has a non-empty value entered. The second argument of the FormControl takes the Sync Validator.

Minlength Validator

Minlength validator requires the control value must not have less number of characters than the value specified in the validator.

For Example, minlength validator ensures that the firstname value has at least 10 characters.

Maxlength Validator

This Validator requires that the number of characters must not exceed the value specified in the validator.

Pattern Validator

This Validator requires that the control value must match the regex pattern provided in the attribute. For example, the pattern ^[a-zA-Z]+$ ensures that the only letters are allowed (even spaces are not allowed). Let us apply this pattern to the lastName

Email Validator

This Validator requires that the control value must be a valid email address. We apply this to the email field

min()

Validator that requires the controlā€™s value to be greater than or equal to the provided number.

max()

Validator that requires the controlā€™s value to be less than or equal to the provided number.

requiredTrue()

Validator that requires the controlā€™s value be true. This validator is commonly used for required checkboxes.

nullValidator()

Validator that performs no operation.

compose()

Compose multiple validators into a single function that returns the union of the individual error maps for the provided control.

composeAsync()

Compose multiple async validators into a single function that returns the union of the individual error objects for the provided control.

Every form element has a FormControl instance associated with it. It exposes the state of form element like valid, dirty, touched etc.

Dirty:

A control is dirty if the user has changed the value in the UI.

Touched:

A control is touched if the user has triggered a blur event on it.

Resetting Forms

The difference between resetForm and reset is that the former will clear the form fields as well as any validation, while the later will only clear the fields. Use resetForm after the form is validated and submitted, otherwise use reset.

ā€œBefore you share anything with them, every friend of yours is a stranger. ā€

Iā€™ve told you what I know and am now waiting for your opinionšŸ‘Œ

Thank you for reading my postšŸ˜Š

--

--