DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
Building Scalable Real-Time Apps with AstraDB and Vaadin
Register Now

Trending

  • Micro Frontends on Monorepo With Remote State Management
  • Cypress Tutorial: A Comprehensive Guide With Examples and Best Practices
  • Five Java Books Beginners and Professionals Should Read
  • Microservices Decoded: Unraveling the Benefits, Challenges, and Best Practices for APIs

Trending

  • Micro Frontends on Monorepo With Remote State Management
  • Cypress Tutorial: A Comprehensive Guide With Examples and Best Practices
  • Five Java Books Beginners and Professionals Should Read
  • Microservices Decoded: Unraveling the Benefits, Challenges, and Best Practices for APIs
  1. DZone
  2. Coding
  3. Frameworks
  4. Getting Started With Angular Reactive Form Validation

Getting Started With Angular Reactive Form Validation

deven rathore user avatar by
deven rathore
·
May. 07, 20 · Tutorial
Like (3)
Save
Tweet
Share
18.19K Views

Join the DZone community and get the full member experience.

Join For Free

Handling user input with forms is the cornerstone of many common applications.

Applications use forms to enable users to log in, to update a profile, to enter sensitive information, and to perform many other data-entry tasks

We will be looking at how Angular handles form Validation in a Reactive Form.

Angular provides two different approaches to handling user input through forms: reactive and template-driven. Both capture user input events from the view, validate the user input, create a form model and data model to update, and provide a way to track changes.

Reactive and template-driven forms process and manage form data differently. Each offers different advantages.

Our main focus is Reactive Form:

Reactive forms provide a model-driven approach to handling form inputs whose values change over time.  It shows you how to create and update a simple form of control, progress to using multiple controls in a group, validate form values. –Angular.io

We are going to create a simple user registration form. 

Prerequisites

Navigate to the folder where you want to create your project file. Open a command window and run the command shown below.

Shell
xxxxxxxxxx
1
 
1
ng new angular-forms-validation --routing=false --style=scss


The command above creates a new Angular application. The option to create the routing module is set to false and style files extension is set to scss.

Navigate to the new project folder and run the command to install bootstrap:

Shell
xxxxxxxxxx
1
 
1
cd angular-forms-validation
2
npm Install bootstrap --save


Add the following import definition in styles.scss file.

JavaScript
 




xxxxxxxxxx
1


 
1
@import "~bootstrap/dist/css/bootstrap.css";



Importing ReactiveFormsModule API

In order to work with Reactive Forms in Angular, we must import ReactiveFormsModule API in the app module file. 

app.module.ts

TypeScript
xxxxxxxxxx
1
 
1
import { ReactiveFormsModule } from '@angular/forms';
2
3
@NgModule({
4
  imports: [
5
    ReactiveFormsModule
6
  ],
7
})
8
export class AppModule { }


Use of FormGroup, ngSubmit, and formControlName in an Angular Template

There is some set of component classes that communicates with Reactive forms to manage the form data. Below is a list of some of them that we will be looking out in this project:

FormGroup FormGroup is a top-level API that maintains the values, properties and validation state of a group of AbstractControl instances in Angular.
FormBuilder It provides helpful methods to create control instances in Angular Reactive Forms.
ngSubmit This event is called when the form is submitted.
FormControl It communicates with an HTML Form element like input or select tag, this API handles the individual form value and validation state.


Required Field Validation

Let’s look at how to handle validation on each of the form fields listed above. In our project folder, open app.component.html and write the code below.

HTML
xxxxxxxxxx
1
 
1
<form [formGroup]="registrationForm" (ngSubmit)="submitRegistrationForm()">
2
</form>


We started by creating our form, and we binded formGroup and ngSubmit classes to it in order to tracks the value and validity state of a group of FormControl instances and to submit the value when the user is done and hits the submit button. 

TypeScript
xxxxxxxxxx
1
16
 
1
<input style="width: 100%;" type="text" formControlName="FullName" placeholder="" name="FullName" autocomplete="off" [ngClass]="{ 'is-invalid': submitted && registrationForm.controls.FullName.errors }" ></div>
2
3
<div *ngIf="submitted && registrationForm.controls.FullName.errors" class="text-danger">
4
    <div *ngIf="registrationForm.controls.FullName.errors.required">
5
    FullName is required
6
    </div>
7
</div>
8
9
<div class="text-center box">
10
  <button>
11
       Create
12
   <div *ngIf="loading" class="spinner-border" role="status">
13
       <span class="sr-only">Loading...</span>
14
    </div>
15
  </button>
16
</div>


We have created our input tag, and we bind formControlName to the input to get the value when a user types. And is-invalid that we bind to our div will automatically determine if an input is good based on the rules placed on it and show an error if the user makes a mistake.

Radio Buttons in Reactive Forms

Let’s look at how we can work with Radio Buttons in our registration form.

To work with Radio Buttons in Angular application, we must set dynamic values in the form control array.

Since the user can select any values, we should use the setValue() method to assign the dynamic values to form a control array. Open app.component.html and write the below code.

HTML
xxxxxxxxxx
1
10
 
1
<!-- Radio Buttons -->
2
<div class="custom-control custom-radio">
3
  <input id="male" type="radio" class="custom-control-input" name="gender"     formControlName="gender" value="male" checked>
4
      <label class="custom-control-label" for="male">Male</label>
5
</div>
6
7
<div class="custom-control custom-radio">
8
   <input id="female" type="radio" class="custom-control-input" name="gender" formControlName="gender" value="female">
9
     <label class="custom-control-label" for="female">Female</label>
10
</div>


In the above code, we created our radio buttons and added some default value to it but we are looking at how to set the selected value of Radio Buttons using Angular Reactive Forms.

TypeScript
xxxxxxxxxx
1
 
1
registrationForm = this.fb.group({
2
  gender: ['male']
3
})


To select the value from the radio button we Passed the radio button value name within the form control array. 

Using FormBuilder API

The FormBuilder service offers 3 useful methods: group(), control(), and array(). These methods generate instances in our component classes including form controls, form groups, and form arrays. Let’s look at how FormBuilder works. Open app.component.ts and write the code below.

TypeScript
xxxxxxxxxx
1
35
 
1
import { Component } from "@angular/core";
2
import { FormBuilder, FormGroup, Validators } from "@angular/forms";
3
@Component({
4
  selector: "app-root",
5
  templateUrl: "./app.component.html",
6
  styleUrls: ["./app.component.scss"]
7
})
8
export class AppComponent {
9
  title = "angular-forms-validation";
10
11
  registrationForm: FormGroup;
12
  invalidlogin: boolean = false;
13
  submitted = false;
14
  loading = false;
15
  constructor(private formBuilder: FormBuilder) {}
16
17
  ngOnInit() {
18
    this.registrationForm = this.formBuilder.group({
19
      FullName: ["", Validators.required],
20
      phone: ["", Validators.required],
21
      email: ["", [Validators.required, Validators.email]],
22
      password: ["", [Validators.required, Validators.minLength(6)]]
23
    });
24
  }
25
26
  submitRegistrationForm() {
27
    this.submitted = true;
28
    this.loading = false;
29
    if (this.registrationForm.invalid) {
30
      return console.log('Account created successfully');
31
    }
32
    this.loading = true;
33
  }
34
35
}


We start by importing FormBuilder, FromGroup, and Validator that we used to track our form.

Then we declared registrationForm variable and assigned the value as FormGroup.

We also called this.registrationForm and passed the Value to FormBulider that will check if the values from our Form has passed the necessary requirement assign to it or not and if passed the Requirement, it will send the value to where ever we want it to but in this project, we console.log the value and if not passed, it will throw an error to the user telling them where they have made a mistake for the user to correct.

Conclusion

In this tutorial, we were able to create a registration form that we used to learn and understand how reactive form validation works in Angular. 

Get the source code from GitHub and play around with ready-made Elegant Registration Form for a better understanding.

Form (document) AngularJS

Published at DZone with permission of deven rathore. See the original article here.

Opinions expressed by DZone contributors are their own.

Trending

  • Micro Frontends on Monorepo With Remote State Management
  • Cypress Tutorial: A Comprehensive Guide With Examples and Best Practices
  • Five Java Books Beginners and Professionals Should Read
  • Microservices Decoded: Unraveling the Benefits, Challenges, and Best Practices for APIs

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com

Let's be friends: