VOOZH about

URL: https://www.geeksforgeeks.org/angular-js/building-complex-forms-using-angular-reactive-form/

⇱ Building Complex Forms Using Angular Reactive Form - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Building Complex Forms Using Angular Reactive Form

Last Updated : 8 Aug, 2024

Imagine you are building a web page where you have to make a Form having fields, such as First Name, Last Name, and so on and you have to handle form inputs, validations, and interactions. Here, using Reactive Forms you define the structure of the form directly in Typescript code rather than HTML template.

Reactive Forms provide a model-driven approach making it easier to make, manage and validate Forms. You can make complex Forms more easily using Reactive Forms than by using Template-driven Driven Forms.

Features of Reactive Forms

  • Form Control: Each field in your form is represented by a FormControl
  • Form Group: You can group related form controls together using FormGroup
  • Form Arrays: For Fields, that need to handle multiple values, you need to add it in 'Form Arrays' likewise, in the below example we are using for Skills.

Approach

  • Create a Reactive Form having input fields for basic information about a User.
  • A Dropdown for State will be added.
  • We will be adding validations for every mandatory field.
  • An input field for password and Confirm Password will be added.
  • The form will only be submitted when all the required fields are filled otherwise, the form will not be submitted.
  • We will be adding styling to the form to make it look Presentable.

Steps to Setup Reactive Forms

Step 1: Run the following command to install Angular CLI

npm install -g @angular/cli

Step 2: Run the following command to initialize the Angular Project

ng new Complex-Forms

Dependencies

"dependencies": {
"@angular/animations": "^18.0.0",
"@angular/common": "^18.0.0",
"@angular/compiler": "^18.0.0",
"@angular/core": "^18.0.0",
"@angular/forms": "^18.0.0",
"@angular/platform-browser": "^18.0.0",
"@angular/platform-browser-dynamic": "^18.0.0",
"@angular/platform-server": "^18.0.0",
"@angular/router": "^18.0.0",
"@angular/ssr": "^18.0.0",
"express": "^4.18.2",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"zone.js": "~0.14.3"
}

Project Structure

👁 Screenshot-2024-08-01-194236
Project Structure

Example: In this example, we are building Complex Forms using Reactive Forms.We will be defining Validations and sometimes a function is created for Validations such as passwordMatchValidator as we have made in the example below. For State Dropdown, we have taken a JSON array having come and names so as to make a dropdown.


To start the application run the following command.

ng serve --open

Output

Comment
Article Tags:

Explore