Angular has been around for quite some time and is one of the most popular front-end frameworks out there. As it's a complete rewrite of the AngularJS framework, (which itself was based on JavaScript) and also written completely in TypeScript, it's very popular amongst developers. So we thought it'd be a good idea to take a look at Reactive Forms, a very important concept in Angular. They're similar to the template-driven forms you might be used to already but offer way more control. Sounds great right? Let’s jump in.
If you look at it visually, then reactive forms are no different from template-driven forms. For example, you can build the exact same thing using the template-driven approach as well as the reactive approach. In template-driven forms, most of the logic for the form itself is maintained inside the template (which is the HTML file). Whereas, for reactive forms, this logic is maintained inside the component code (which is the TypeScript file). Template-driven forms are also asynchronous in nature whereas reactive forms are mostly synchronous.
Now, let’s create a simple reactive form in Angular. To do this, we're going to start at the end. See below for the end product we'll be building. It has just three fields, first name, last name, and age. We're starting simple, but feel free to add more fields the more comfortable you get. We have some basic validation checks to check whether fields are empty or not and it will display an error message. Once everything has been entered, it should display an alert message which will show the details that were entered.
We already know that this form can be built easily using template-driven forms as well as reactive forms and both will visually look the same. But if you're looking for that extra oomph, then go for the reactive form. Reactive forms have the form defined inside the component and linked to the template, whereas it is the other way around for template-driven forms.
First of all, we need an Angular project, for implementing Reactive forms. This can be created by using the following command:
ng new project_name
This will create a new Angular project for you. It will ask whether you need Angular routing and the type of stylesheets you want to use. You can choose whatever you’re comfortable with here. (We're assuming that you already have Angular CLI installed, and a package manager like node or yarn for installing dependencies.)
The next step is to install Bootstrap. This is just to make our forms look a little nicer, and is completely optional. To install Bootstrap, use the following command:
npm install bootstrap
Now, to use it in our application, we need to import the stylesheet inside our main styles.css file. To do that use the following line of code:
@import '~bootstrap/dist/css/bootstrap.min.css';
And to be able to use Reactive Forms inside our project, we need to import the ReactiveFormsModule from @angular/forms. This should be specified inside the imports section of our app.module.ts file.
Now that we’ve got the initial setup out of the way, it's high time we started coding. Go inside your app.component.ts file and create an attribute called userDetails of the type FormGroup. This will be used to initialise the form and associate all the form controls. While the component is being loaded, inside the ngOnInit() lifecycle hook, we call a method to initialise the form. This method creates a new FormGroup object and creates three new FormControls inside it.
A FormControl is just a field inside the form and it is defined programmatically. It can take three arguments. The first one is the default value, the second one is the type of validation (minimum length, required field, etc) and the third one can be any async validation that you want to add. Multiple validators can be specified as an array as well.
The onSubmit() method, stores the values inside the form group into a const and then shows the alert on the screen based on the values entered by the user. We use template literals from ES6 to access the variables using the ${} notation and backticks.
We have an additional method – isValidInput() – that accepts the fieldname and returns true or false depending on whether it is valid. This is checked using the form controls we initialised earlier. Now, let’s take a look at the template code in HTML.
This is just the first half of the form, but it contains everything that we need to show the capabilities of Reactive forms. Inside the form element, we are binding the formGroup property with the userDetails using property binding. This uses the square brackets to specify the property to bind to. Next up, we have event binding. When the form is submitted, the ngSubmit event is triggered, and we bind this to the onSubmit() method inside our component code.
Moving down, you can see that we have a label for our field followed by the input element. Here, we give it an attribute of formControlName and give it the corresponding name that we initialised in the component code. The next div tag checks for the validations and displays an error message. If you check the component code, you can see that we have three fields, each of which has a default value of null, followed by a required validation. This means that the specific field needs to have a value in the form, otherwise an error will be shown.
Lastly, we have the button of type submit that will trigger the ngSubmit hook when it is clicked. With that, we have completed coding up a simple reactive form in Angular. We have seen what reactive forms are and how we can implement them. But why do we need them?
Now that you’ve gone through the code for a Reactive form you might have realized that the template code is much cleaner and precise. This allows for easier testing in comparison to template-driven forms. The fact that all the validation code is moved from the template code to the component code also makes it a much natural way to write code.
It really is easy when you break it down. We've covered enough about reactive forms in Angular to start building your own forms easily. The code for this project is also available here. Stay tuned for the next one. Happy coding!
Like what you've read or want more like this? Let us know! Email us here or DM us: Twitter, LinkedIn, Facebook, we'd love to hear from you.