AngularJS (62 Blogs) Become a Certified Professional

How To Use Reactive Forms in Angular?

Published on Aug 14,2024 22 Views

Sunita Mallick
Experienced tech content writer passionate about creating clear and helpful content for... Experienced tech content writer passionate about creating clear and helpful content for learners. In my free time, I love exploring the latest technology.

Angular is a highly used framework for developing web applications. It has two ways to handle forms. The two major categories of forms that are commonly used in form development are template-driven forms and angular reactive forms. As a matter of fact, reactive forms render more control and flexibility as compared to reactive forms. They are especially convenient when it comes to complex forms. In this article, we will learn about the use of reactive forms within Angular applications.

Table of Contents:

Step 1 — Setting Up the Project

First, we have to set up an Angular app. This is where we’ll write our code. To do this, you will require Node. Js are installed in your system to execute the project development properly. Node.Js is designed to let you run JavaScript on your machine and assist in managing dependencies relevant to your project.

1. Install Node.js:

On the official Node.JS website, one can download the latest version. You can also find various archive versions of Node. JS. You can install the required version according to your project needs. After downloading it, follow the installation instructions that you will find accompanying it.

2. Create a New Project:

For this tutorial, you’ll be using a command line tool – like Command Prompt for Windows 10 or Terminal for macOS.  You have to type a particular command in the command line to generate or build an Angular project. This command creates a new project, to begin with some default configurations. For a start, it makes things easier to start working on your app.

npx @angular/cli new angular-reactive-forms-example –style=css –routing=false –skip-tests

3. Navigate to Your Project:

Once you have completely created the project, then you have to open it by going into the project directory. This is like if you open a folder to take a look at what is inside the folder.

cd angular-reactive-forms-example

4. Use ReactiveFormsModule:

Angular has different modules for different purposes or rather for different tasks that are to be performed. For reactive forms, we have the ReactiveFormsModule.  It is a very popular module among the public. This module provides you with the ability to create Reactive forms.

Do you know about how to add a form to the component template? If not then read more to understand. 

Step 2 — Adding a Form to the Component Template

Next, let us add a form to our application so that users can enter data into it. Text-input fields are used to retrieve user inputs such as name, email, or message. There are 3 ways to perform step 2: 

1. Open the Template File:

Angular applications are built of components, and each needs to have an HTML template file where you specify what it looks like. Finally, this file should be terminated with a ‘.html’.

2. Add Form Elements:

In the template file, please insert HTML tags that are required to develop a form. Typically, a form will comprise input fields and a submit button. For instance, they can include the fields where one can type his/her name, e-mail, and the message.

3. Bind Form to Component:

To make the form reactive, you need to connect it to your component class. This is because the form data is contained in the component, which makes it easier to handle validation and submission.

Let’s dive down and learn about step 3 to know on building the component class. 

Step 3 — Building the Component Class

Next, we need to define the form in the component class. The component class is the class in which all the logic of your component is implemented.

1. Create a Form Group:

Form group is somewhat similar to div; it’s used to contain form controls, which are like input fields. You can define a form group in the component class. Then, you need to add the form controls directly to the group.

1. Create a Form Group:
Form group is somewhat similar to div; it’s used to contain form controls, which are like input fields. You can define a form group in the component class. Then, you need to add the form controls directly to the group.

this.myForm = new FormGroup({
name: new FormControl(”),
email: new FormControl(”),
message: new FormControl(”)
});


2. Initialize Form Controls:

Every input field that you design in your form is a form control. You develop these controls at the component class and define their default values.
3. Handle Form Submission:
This is an event that you must manage when the user has submitted the form. To handle the form data, you can create the method in the component class, which you can log or send to the specified server.

Wondering after step 3 what will you do to update the component class? Then you should check below step 4 on updating the component class to use FormBuilder.

Step 4 — Updating the Component Class to Use FormBuilder

Using the FormBuilder can help in making the creation of forms a simpler process. FormBuilder is a service that helps to use less code when generating form groups and form controls.

1. Inject FormBuilder:
Firstly, you have to make FormBuilder available in your component. You can achieve this by integrating it into the component’s constructor.

2. Create Form Group with FormBuilder:
You can use FormBuilder instead of manually creating form controls using HTML code because it helps you to define your form group and controls in a shorter way.

Step 5 — Updating the Component Class to Use Validators

The use of validation is also significant as it provides the user with an option to ensure that they fill out the form correctly. Fortunately, there is a way to facilitate this in Angular, and that is by using built-in validators.

1. Add Validators:
Validators are functions that check if the user’s input meets certain rules. For instance, you might want to verify that the email field holds the correct email address.

2. Set Validation Rules:
You need to define these validation rules at design time when designing the form controls. These rules can be, for example, obligatory fields, the minimum number of characters you must write in the message or even the correct email address format.

this.myForm = this.fb.group({
  name: ['', Validators.required],
  email: ['', [Validators.required, Validators.email]],
  message: ['', [Validators.required, Validators.minLength(15)]]
});

3. Check Validity:
To see whether the form or any form control is valid, you can look up their validity properties. It assists in determining whether you can submit the form or display the error messages properly. You can understand these validations from any Angular JS Course.

Step 6 — Accessing Form Value and Validity in the Template

Having validation messages in the template allows people to see what needs to be changed.

1. Form Control State:
Check if a form control is valid, or dirty in the template.

2. Error Messages:
Show error messages based on the form control state. For example, show “Please provide a valid email address” if the email field is invalid.

3. Disable Submit Button:
Disable the submit button until the form is valid. This helps users fix errors before submitting.

Conclusion

We learned how to use reactive forms in Angular. We created a project, made a form, and added validation. Reactive forms give more control and are good for complex forms. Follow these steps to create strong forms. For more details, check the official Angular documentation. Thank you!

Upcoming Batches For Angular Certification Training Course Online
Course NameDateDetails
Angular Certification Training Course Online

Class Starts on 21st September,2024

21st September

SAT&SUN (Weekend Batch)
View Details
Angular Certification Training Course Online

Class Starts on 12th October,2024

12th October

SAT&SUN (Weekend Batch)
View Details
Comments
0 Comments

Join the discussion

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.

image not found!
image not found!

How To Use Reactive Forms in Angular?

edureka.co