How To Use Reactive Forms in Angular?
Last Updated :
13 Aug, 2024
In Angular, the forms are an important part of handling user input and validation. Reactive Forms offers a model-driven approach that provides greater control and flexibility by managing form controls, validation, and data binding directly within the component class.
Core Components
- FormGroup: Represents a collection of FormControl instances. It is used to group related form controls, such as those in a form.
- FormControl: Represents a single form control. It manages the value and validation status of an individual input field.
- FormArray: Manages an array of FormControl or FormGroup instances, allowing for dynamic and repeatable form controls.
- Validators: Provides built-in validation functions, such as required, minLength, email, and min, which can be used to validate form controls.
Approach
- Import ReactiveFormsModule in the AppModule.
- We will create FormGroup and FormControl instances within the component's ngOnInit method, defining form controls and their validations.
- We then bind the form model to the template using [formGroup] and formControlName and handle form submission with a method that processes the form data.
Steps to Use Reactive Forms in Angular
Step 1: Install Angular CLI
If you haven’t installed Angular CLI yet, install it using the following command
npm install -g @angular/cli
Step 2: Create a New Angular Project
ng new form-app --no-standalone
cd form-app
Step 3: Create Standalone Component
Create a standalone component. You can generate a standalone component using the Angular CLI:
ng generate component user-form
Dependencies
"dependencies": {
"@angular/animations": "^18.1.4",
"@angular/common": "^18.1.4",
"@angular/compiler": "^18.1.4",
"@angular/core": "^18.1.4",
"@angular/forms": "^18.1.4",
"@angular/platform-browser": "^18.1.4",
"@angular/platform-browser-dynamic": "^18.1.4",
"@angular/router": "^18.1.4",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"zone.js": "~0.14.10"
}
Project Structure
Folder StructureExample: In this example, we are using Reactive Forms in Angular to create a user form with fields for name, email, and age. The form includes validation rules and displays error messages if the inputs are invalid. After submission, if the form is valid, the form data is shown centered below the submit button. This approach uses Angular’s form controls and validation mechanisms to handle user inputs and feedback effectively.
HTML
<!-- src/app/user-form/user-form.component.html -->
<h1 class="header">GeeksforGeeks</h1>
<h3>Reactive Forms in Angular</h3>
<form [formGroup]="userForm" (ngSubmit)="onSubmit()">
<!-- Existing Fields -->
<label for="name">Name:</label>
<input id="name" type="text" formControlName="name">
<div *ngIf="userForm.get('name')!.invalid && userForm.get('name')!.touched">
Name is required and must be at least 3 characters long.
</div>
<label for="email">Email:</label>
<input id="email" type="email" formControlName="email">
<div *ngIf="userForm.get('email')!.invalid && userForm.get('email')!.touched">
Enter a valid email address.
</div>
<label for="age">Age:</label>
<input id="age" type="number" formControlName="age">
<div *ngIf="userForm.get('age')!.invalid && userForm.get('age')!.touched">
Age is required and must be 18 or older.
</div>
<!-- New Fields -->
<label for="phoneNumber">Phone Number:</label>
<input id="phoneNumber" type="text" formControlName="phoneNumber">
<div *ngIf="userForm.get('phoneNumber')!.invalid &&
userForm.get('phoneNumber')!.touched">
Phone number is required and must be 10 digits.
</div>
<label for="address">Address:</label>
<input id="address" type="text" formControlName="address">
<div *ngIf="userForm.get('address')!.invalid && userForm.get('address')!.touched">
Address is required.
</div>
<label for="country">Country:</label>
<select id="country" formControlName="country">
<option value="" disabled>Select your country</option>
<option *ngFor="let country of countries" [value]="country">{{ country }}</option>
</select>
<div *ngIf="userForm.get('country')!.invalid && userForm.get('country')!.touched">
Country is required.
</div>
<label for="dateOfBirth">Date of Birth:</label>
<input id="dateOfBirth" type="date" formControlName="dateOfBirth">
<div *ngIf="userForm.get('dateOfBirth')!.invalid &&
userForm.get('dateOfBirth')!.touched">
Date of Birth is required.
</div>
<label for="password">Password:</label>
<input id="password" type="password" formControlName="password">
<div *ngIf="userForm.get('password')!.invalid && userForm.get('password')!.touched">
Password is required and must be at least 6 characters long.
</div>
<label for="confirmPassword">Confirm Password:</label>
<input id="confirmPassword" type="password" formControlName="confirmPassword">
<div *ngIf="userForm.get('confirmPassword')!.invalid &&
userForm.get('confirmPassword')!.touched">
Confirm Password is required.
</div>
<div *ngIf="userForm.errors?.['passwordsMismatch']">
Passwords do not match.
</div>
<button type="submit" [disabled]="userForm.invalid">Submit</button>
</form>
<div *ngIf="userForm.valid" class="form-data">
<pre>{{ userForm.value | json }}</pre>
</div>
HTML
<!--// src/app/app.component.html-->
<app-user-form></app-user-form>
CSS
/* src/app/user-form/user-form.component.css */
form {
max-width: 400px;
margin: 20px auto;
padding: 20px;
border: 1px solid #ccc;
border-radius: 5px;
}
label {
display: block;
margin-bottom: 5px;
}
input,
select {
width: 100%;
padding: 8px;
margin-bottom: 10px;
border: 1px solid #ccc;
border-radius: 4px;
}
div {
color: red;
margin-bottom: 10px;
}
button {
width: 100%;
padding: 10px;
background-color: #007bff;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
}
button:disabled {
background-color: #ccc;
}
.header {
color: green;
text-align: center;
}
h3 {
text-align: center;
}
.form-data {
text-align: center;
margin-top: 20px;
}
JavaScript
// src/app/app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { ReactiveFormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { UserFormComponent } from './user-form/user-form.component';
@NgModule({
declarations: [
AppComponent,
UserFormComponent
],
imports: [
BrowserModule,
ReactiveFormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
JavaScript
// src/app/user-form/user-form-component.spec.ts
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { UserFormComponent } from './user-form.component';
describe('UserFormComponent', () => {
let component: UserFormComponent;
let fixture: ComponentFixture<UserFormComponent>;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [UserFormComponent]
});
fixture = TestBed.createComponent(UserFormComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
JavaScript
// src/app/user-form/user-form.component.ts
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators, ValidatorFn, AbstractControl }
from '@angular/forms';
@Component({
selector: 'app-user-form',
templateUrl: './user-form.component.html',
styleUrls: ['./user-form.component.css']
})
export class UserFormComponent implements OnInit {
userForm!: FormGroup;
countries = ['United States', 'India', 'United Kingdom', 'Australia'];
ngOnInit() {
this.userForm = new FormGroup({
name: new FormControl('', [Validators.required, Validators.minLength(3)]),
email: new FormControl('', [Validators.required, Validators.email]),
age: new FormControl('', [Validators.required, Validators.min(18)]),
phoneNumber: new FormControl('', [Validators.required,
Validators.pattern(/^\d{10}$/)]),
// Example pattern for a 10-digit phone number
address: new FormControl('', [Validators.required]),
country: new FormControl('', [Validators.required]),
dateOfBirth: new FormControl('', [Validators.required]),
password: new FormControl('', [Validators.required, Validators.minLength(6)]),
confirmPassword: new FormControl('', [Validators.required])
}, { validators: this.passwordsMatch() });
}
passwordsMatch(): ValidatorFn {
return (group: AbstractControl): { [key: string]: any } | null => {
const password = group.get('password')?.value;
const confirmPassword = group.get('confirmPassword')?.value;
return password === confirmPassword ? null : { passwordsMismatch: true };
};
}
onSubmit() {
if (this.userForm.valid) {
console.log('Form Submitted!', this.userForm.value);
} else {
console.log('Form not valid');
}
}
}
JavaScript
// src/app/app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'reactive-forms-example';
}
Steps to run this Project
ng serve --open
Output
Similar Reads
How to use Mat-Dialog in Angular ?
Introduction:Angular Material is a UI component library that is developed by the Angular team to build design components for desktop and mobile web applications. In order to install it, we need to have angular installed in our project, once you have it you can enter the below command and can downloa
3 min read
How to Implement Angular Forms?
Creating a Form in Angular includes the use of directives such as ngSubmit and ngModel. We will be using a functional component to render the elements. Various HTML elements are created in the project. To implement the project we will create the styling using CSS. Prerequisites:Functional Components
4 min read
How to get the value of the form in Angular ?
In this article, we are going to see how to get value from the form in Angular 10. We will use AbstractControl value property to get the form value in an object. Syntax: form.value Return Value: object: It is an object containing form value Approach: Create the Angular app to be usedIn app.component
1 min read
How To Use OnChanges In Angular?
Angular is a powerful framework for building dynamic web applications, and one of its core features is the ability to manage and react to changes in component data. One of the key lifecycle hooks in Angular for responding to changes in input properties is the OnChanges lifecycle hook. This hook is h
3 min read
How to use jQuery in Angular ?
In this tutorial, we will learn how we can use jQuery with Angular. There are two ways in which we can use jQuery with Angular as discussed below: Table of Content By installing jQuery using the npm commandUsing jQuery CDN to use itBy installing jQuery using the npm commandYou can install the jQuery
2 min read
Angular forms FormGroupDirective
In this article, we are going to see what is FormGroupDirective in Angular 10 and how to use it. FormGroupDirective is used to Bind an existing FormGroup to a DOM element. Syntax: <form [FormGroup] ="name"> Exported from: ReactiveFormsModule Selectors: [FormGroup] Approach: Create the Angular
1 min read
Template Driven Form vs Reactive Form in Angular.
Angular provides two main approaches for creating forms: Template-Driven Forms and Reactive Forms. In this article, we'll see both methods, highlighting their features, and providing code examples. We'll also compare them side by side to help you understand when to use each. Template-Driven FormTemp
4 min read
How to Build Dynamic Forms in React?
React, a popular library built on top of javascript was developed by Facebook in the year 2013. Over the coming years, React gained immense popularity to emerge as one of the best tools for developing front-end applications. React follows a component-based architecture which gives the user the ease
9 min read
How to use $scope.$apply() in AngularJS ?
In this article, we will be discussing the $apply() function & how to use it in angularjs. In AngularJS, $apply() function is used to evaluate expressions outside of the AngularJS context (browser DOM Events, XHR). Moreover, $apply has $digest under its hood, which is ultimately called whenever
3 min read
How to use Angular Material in Angular 17?
Angular Material is a comprehensive UI component library designed specifically for Angular applications. With its large collection of pre-built components and seamless integration with Angular, Angular Material simplifies the process of creating visually appealing and responsive user interfaces. In
2 min read