Let's Develop An Angular Application - Introduction To Angular Reactive Forms

Introduction

 
In my previous articles, I have explained Angular template-driven forms and validation.
 
In this article, we will learn about Angular reactive forms.
 
It would be good to have a basic understanding of angular template-driven forms in order to learn reactive forms easily.
 
You can refer my previous articles to learn template-driven forms by clicking the below links:
In a template-driven form approach, Angular will automatically generate the form model by using the form groups and form controls instances. We use the ngModel directive for two way binding to keep the user inputs and data model properties in sync.
 
But in the case of reactive forms, we will create the form model by creating the form groups and form controls instances in our component class. Then, we will bind the template to the form model. Here are template is not modifying the data model directly.
 

Create an Angular Project

 
Let’s create an Angular project.
 
If you want to read more about Angular project architecture and installation, please read my previous articles.
  • Open command prompt
  • Navigate to your folder using the CD command
  • Execute the command ng new ProjectReactiveForms
image-content
 
Here, 'ProjectReactiveForms’ is the name for my project. You can choose your own name for the project.
 
Navigate to the project folder.
 
Open the project in any editor, such as Visual Studio code.
 
The project structure will look like the below screenshot.
 
image-content
 

Create a Component

 
Open terminal by pressing the keys Ctrl + ` or View->Terminal
 
Execute the command ‘ng generate component reative-form’
 
image-content
 
The component will be created under src>app folder. Please refer the screenshot below
 
image-content
 
So far, we have created an Angular project and a component.
 
Next, we need to create a form model.
 

Create Form Model

 
A reactive form should have at least one form group. It is called the root form group.
 
The root form group contains the properties to keep the states, default values, and properties to retain the user inputs and set of FormControls for each input field.
 
We can use the formGroup and formControl to create the form model.
 
We can follow the below steps to create the formModel 
  1. Open the app.module file
  2. Import the ReactiveFormsModule from @angular/forms and add the ReactiveFormsModule into the import array.

    Please refer to the screenshot below.

    image-content

  3. Open the component file
  4. Create a property ‘userForm’ of type FormGroup.

    This property will be the reference to the form model

  5. Import the FormGroup class from ‘@angular/forms’.
Please refer to the screenshot below.
 
image-content
 
Next, we need to assign the 'userForm' property to the new instance of the FormGroup.
 
We will do it in the 'ngOnInit' life cycle hook.
 
Here, we are using the ngOnInit life cycle hook instead of the constructor.
 
This is because we need to make sure that the component and template are initialized before creating the form Model.
 
Please refer to the below screenshot.
 
image-content
 
As you can see in the above screenshot, in the FormGroup constructor we are passing an object as a parameter.
 
We can use this parameter to pass the FromControls and nested FormGroups as key-value pairs
 
We need to create FormControls for the name, emailID, gender, payment type, and notification.
 
Please refer to the below screenshot.
 
image-content
 
Also, import the FormControl from ‘@angular\forms’
 
We have created the basics of the model successfully.
 

Create Registration Form Template

 
Let’s create the template file next.
 
I have created a user registration form template file for my previous articles.
 
Please read the below article to read about template-driven articles.
I am going to use the same template structure for reactive form projects as well.
 
To improve the UI, I am installing bootstrap for this project.
 

Install Bootstrap

 
Let’s install bootstrap to add simple bootstrap CSS classes.
 
Execute the CLI command npm install –save bootstrap
 
This will take a few seconds to install the bootstrap library.
 
Then, add the bootstrap CSS file path in Angular.json file.
 
image-content
 

Create a simple Angular form

 
Let’s create a simple form.
 
Open the ‘reactive-form.component.html’
 
Then I added 2 input elements to type the user name and email.
 
Then I added 2 radio buttons for gender.
 
image-content
 
Here I have added a few div elements and CSS classes to the input elements.
 
This will make the file a bit bulky.
 
But they are added to improve the appearance only.
 
Here, the ‘formGroup directive is used to bind the form element in the template to the root form group of the form model
 
<form [formGroup]="userForm">
 
‘userForm’ is the form model property defined in the component class.
 
Save the files and check the result in the browser.
 
The result will be like the below screenshot.
 
image-content
 
We can add a few more controls to get more information from the user.
 
Don’t worry about the bootstrap style classes. We can refer the bootstrap documentation to understand various form controls
 
Click the link to visit bootstrap documentation.
 
I have added dropdown control by using the below HTML statements.
  1. <div class="form-group">    
  2.     <label for="paymentMode">Payment Mode</label>    
  3.     <select class="form-control" id="paymentMode">    
  4.        <option>Monthly</option>    
  5.        <option>Quarterly</option>    
  6.        <option>Yearly</option>    
  7.     </select>    
  8. </div>     
I have copied the statements from the bootstrap documentation site.
 
Then we need to add checkbox control to enable notifications.
 
Please refer the HTML statements to add a check box below. 
  1. <div class="form-check">    
  2.    <input class="form-check-input" type="checkbox" value="" id="enable_notification" name="notification" >    
  3.    <label class="form-check-label" for="enable_notification"> Enable Notification </label>    
  4. </div>     
Finally, add a button control as below.
  1. <div class="form-group row">    
  2.     <div class="col-sm-10">    
  3.           <button type="button" class="btn btn-primary">Register</button>    
  4.     </div>    
  5. </div>     
Now the template file will look like below screenshot
 
Save the file and check the browser. We will get a result as shown in the below screenshot.
 
image-content
 
We have created a decent-looking form!
 

Link the template and form model

 
The next step is to connect each input controls in the registration form to the properties of the form model.
 
We already linked the root form group of the form model to the form element in the template using ‘formGroup’ directive.
 
So the form model properties will be available inside the template.
 
We can bind each form model properties to the input controls using the ‘formControlName’ directive .
 
Please refer to the screenshot below. 
 
image-content
 
Here, the 'name' and 'email' are the form control properties defined inside the component class.
 
image-content
 
I have added the 'formControlName' directive to all the input elements and added the 'ngSubmit event binding to save the user data.
 
Please refer to the screenshot below.
 
image-content
image-content
 
On clicking the Register button, saveData() method will be executed.
 
Inside the saveData() method, I’m just writing the form mode values to the console.
 
But, we can write any other code logic to save the user data. 
 
Please refer to the screenshot below.
 
image-content
 
Save the project and fill the form and click the ‘Register’ button.
 
Open the developer console window to see the user data in the form model.
 
Please refer the screenshot below:
 
image-content
 

setValue() and patchValue() methods

 
Let’s learn how to set the user data from the component class.
 
We can use the setValue() method to set the values to the form model properties.
 
setValue() method is used to provide values for all the form controls defined in the form model.
 
We should provide values for all the controls. Otherwise it will generate an error.
 
Please refer to the new method to set values to the form model.
 
image-content
 
The patchValue() method is used to provide value for any specific controls of the form model.
  1. this.userForm.patchValue({notification:true});  
Next, we need to create a new button in the template to call this method.
 
Please refer to the screenshot below.
 
image-content
 
Save the files and check the result in the browser.
 
Please refer to the screenshot below.
 
image-content
 
If we click the Get Data button in the registration form, the getData() method will be executed and the form model will be updated with the new data.
 

Conclusion

 
We have created an Angular project, installed bootstrap, created a component, and created a user registration form using Angular reactive forms approach.
 
Then we created the custom form model using FormGroup and FormControls.
 
We also created a method for assigning values to the form model using setValue() and patchValue() methods.
 
Happy Learning