VOOZH about

URL: https://www.geeksforgeeks.org/angular-js/how-to-use-reactive-forms-in-angular/

⇱ How To Use Reactive Forms in Angular? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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

  1. FormGroup: Represents a collection of FormControl instances. It is used to group related form controls, such as those in a form.
  2. FormControl: Represents a single form control. It manages the value and validation status of an individual input field.
  3. FormArray: Manages an array of FormControl or FormGroup instances, allowing for dynamic and repeatable form controls.
  4. 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

👁 PS
Folder Structure

Example: 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.


Steps to run this Project

ng serve --open

Output

Comment
Article Tags:

Explore