Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • AngularJS Tutorial
  • AngularJS Directives
  • AngularJS Functions
  • AngularJS Filters
  • AngularJS Examples
  • AngularJS Interview Questions
  • Angular ngx Bootstrap
  • AngularJS Cheat Sheet
  • AngularJS PrimeNG
  • JavaScript
  • Web Technology
Open In App
Next Article:
Purpose of the FormsModule in Angular
Next article icon

Purpose of the FormsModule in Angular

Last Updated : 22 Mar, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Forms are widely used in web applications that allow you to provide the data, submit the forms, and interact with the application. In Angular for handling the forms, we use Forms Module which imports several powerful tools for creating, managing, and validating forms. In this article, we'll cover the purpose of the forms module, syntax, concepts, and examples related to Angular forms.

Table of Content

  • What is FormsModule?
  • Type of Forms
  • Purpose of Forms Module
  • Form Handling using Template Driven forms.
  • Form Handling using Reactive Forms.

What is FormsModule?

FormsModule is a built-in Angular module provided by @angular/forms package. It enables two-way data binding, form validation, and other form-related functionalities within Angular applications. By importing and including FormsModule in your Angular application, you gain access to a range of directives, services, and utilities that streamline the process of working with forms.

Syntax: To use Forms module, we first have to import it into the app.module.ts from @angular/forms.

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

@NgModule({
// Other modules ...
imports: [BrowserModule, FormsModule],
})
export class AppModule {}

Type of Forms

1. Template-Driven Forms

Template-driven forms mainly depends on angular directives. It relies on two-way data binding using "[(ngModel)]" directive allowing us to interact with the component directly. Here the form controls are automatically and state of the form is tracked by angular itself.

2. Reactive Forms

Reactive forms provide the direct access to the underlaying form's object model. Here user have to create instances of FormControl, FormGroup and FormArray explicitly allowing more control and flexibility.

Purpose of Forms Module

  • Two-way Data Binding: One of the primary purposes of FormsModule is to provide two-way data binding between form controls and component properties. With two-way data binding, changes made in the template reflect in the component class and vice versa, enabling seamless synchronization of data between the view and the component.
  • Form Validation: Angular provides powerful form validation capabilities through FormsModule. It offers both template-driven and reactive form validation techniques. With FormsModule, you can easily implement built-in validators such as required, min, max, pattern, etc., as well as create custom validators to enforce specific validation rules.
  • Form Controls and Directives: FormsModule provides a set of directives and form controls that simplify the creation and management of forms in Angular applications. Directives like ngModel, ngForm, and ngModelGroup enable easy binding, grouping, and validation of form controls. Additionally, form controls like input, select, and textarea are enhanced with additional features and functionality when used within FormsModule.
  • Handling Form Submission: Another crucial aspect of FormsModule is handling form submission. It provides utilities to track the state of form controls, detect form submission events, and retrieve form data. This simplifies the process of submitting form data to backend services and handling responses effectively.
  • Error Handling and Feedback: FormsModule helps in displaying error messages and providing feedback to users during form interaction. It enables the dynamic display of validation errors, allowing users to identify and rectify input errors in real-time, thereby enhancing the overall user experience.

Example 1: Form Handling using Template Driven forms.

In this example, we'll see form submission and handling of form data using Template Driven forms.

Step 1: Create a new Angular project by running the below command.

ng new <project_name>

Folder Structure:

project_struc1
Project Structure

Dependencies:

"dependencies": {
"@angular/animations": "^17.3.0",
"@angular/common": "^17.3.0",
"@angular/compiler": "^17.3.0",
"@angular/core": "^17.3.0",
"@angular/forms": "^17.3.0",
"@angular/platform-browser": "^17.3.0",
"@angular/platform-browser-dynamic": "^17.3.0",
"@angular/platform-server": "^17.3.0",
"@angular/router": "^17.3.0",
"@angular/ssr": "^17.3.0",
"express": "^4.18.2",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"zone.js": "~0.14.3"
},
"devDependencies": {
"@angular-devkit/build-angular": "^17.3.0",
"@angular/cli": "^17.3.0",
"@angular/compiler-cli": "^17.3.0",
"@types/express": "^4.17.17",
"@types/jasmine": "~5.1.0",
"@types/node": "^18.18.0",
"jasmine-core": "~5.1.0",
"karma": "~6.4.0",
"karma-chrome-launcher": "~3.2.0",
"karma-coverage": "~2.2.0",
"karma-jasmine": "~5.1.0",
"karma-jasmine-html-reporter": "~2.1.0",
"typescript": "~5.4.2"
}

Code Example: Add the following codes in the required files.

HTML
<!-- app.component.html -->  <form #userForm="ngForm" (ngSubmit)="onSubmit()">     <label for="name">Name:</label>     <input type="text" id="name" name="name" [(ngModel)]="user.name" required>      <label for="email">Email:</label>     <input type="email" id="email" name="email" [(ngModel)]="user.email" required>      <button type="submit">Submit</button> </form> <h3>User Details</h3> <p>{{userDetails}}</p> 
JavaScript
// app.module.ts  import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser';  import { AppComponent } from './app.component'; import { FormsModule } from '@angular/forms';  @NgModule({     declarations: [AppComponent],     imports: [BrowserModule, FormsModule],     providers: [],     bootstrap: [AppComponent], }) export class AppModule { } 
JavaScript
// app.component.ts  import { Component } from '@angular/core';  @Component({     selector: 'app-root',     templateUrl: './app.component.html',     styleUrls: ['./app.component.css'], }) export class AppComponent {     user = { name: '', email: '' };     userDetails = 'Loading...';     onSubmit() {         this.userDetails =             'User name is ' + this.user.name + ' and email is ' + this.user.email;     } } 

Output:

trusting-brahmagupta-CodeSandbox-GoogleChrome2024-03-1323-02-15-ezgifcom-video-to-gif-converter
Output for example 1

Example 2: Form Handling using Reactive Forms.

In this example, we'll see form submission and handling of form data using Reactive forms.

Code Example: Add the following codes in the respective files.

HTML
<!-- app.component.html -->  <form [formGroup]="myForm" (ngSubmit)="onSubmit()">     <label for="name">Name:</label>     <input type="text" id="name" formControlName="name">      <label for="email">Email:</label>     <input type="email" id="email" formControlName="email">      <button type="submit">Submit</button> </form> <h3>Form Details</h3> <p>{{formDetails}}</p> 
JavaScript
// app.module.ts  import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser';  import { AppComponent } from './app.component'; import { FormsModule, ReactiveFormsModule } from '@angular/forms';  @NgModule({     declarations: [AppComponent],     imports: [BrowserModule, FormsModule, ReactiveFormsModule],     providers: [],     bootstrap: [AppComponent], }) export class AppModule { } 
JavaScript
//app.component.ts   import { Component } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; @Component({     selector: 'app-root',     templateUrl: './app.component.html',     styleUrls: ['./app.component.css'], }) export class AppComponent {     myForm: FormGroup = {} as FormGroup;     formDetails: string = 'loading...';     constructor(private fb: FormBuilder) { }      ngOnInit() {         this.myForm = this.fb.group({             name: ['', [Validators.required]],             email: ['', [Validators.required, Validators.email]],         });     }      onSubmit() {         this.formDetails =             'Name: ' + this.myForm.value.name + ' Email:' + this.myForm.value.email;     } } 

Output:

trusting-brahmagupta-CodeSandbox-GoogleChrome2024-03-1323-14-09-ezgifcom-video-to-gif-converter
Output for example 2

Next Article
Purpose of the FormsModule in Angular

H

himanshusharma11199
Improve
Article Tags :
  • Web Technologies
  • AngularJS
  • AngularJS-Questions

Similar Reads

    Purpose of the ngOnInit() method in Angular
    ngOnInit is a lifecycle hook in Angular that is called after the constructor is called and after the component’s inputs have been initialized. It is used to perform any additional initialization that is required for the component. ngOnInit is commonly used to call services or to set up subscriptions
    3 min read
    Purpose of NgModule Decorator in Angular
    The NgModule decorator in Angular is like a blueprint for organizing and configuring different parts of your application. It's like a set of instructions that tells Angular how to assemble the various components, directives, pipes, and services into cohesive units called modules. These modules help
    5 min read
    What is the AppModule in Angular ?
    In Angular, AppModule plays an important role as the entry point to an Angular application. In this article, we'll learn about what AppModule is, its structure, and its significance in Angular applications. We'll also look at some examples to have a clear understanding. Table of Content What is AppM
    4 min read
    Purpose of Validators class in Angular
    The Validators class in Angular provides a set of built-in validation functions that can be used to validate form controls and user input. It is part of the @angular/forms module and is commonly used in conjunction with Angular's Reactive Forms or Template-driven Forms. PrerequisitesTypeScriptAngula
    4 min read
    Purpose of ProvidedIn in Angular
    Angular's dependency injection system is a powerful mechanism that helps manage dependencies between components, services, and other parts of the application. One important aspect of this system is the providedIn property, which determines the scope and visibility of a service or module. In this art
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences