How to Use Reactive Forms in Angular
Table of contents
Angular has several benefits over other platforms such as a component-based architecture that results in a higher quality of code. Other benefits include a platform-agnostic philosophy, or simply, a ‘mobile-first approach and high performance. It is a resourceful ecosystem and has higher credibility due to long-term Google support.
But the question right now is, what do application-building frameworks like Angular require forms for? Forms used in applications enable their users to perform several data-entry tasks. These tasks range from logging in and updating a profile to even entering sensitive information. Thus, using forms to handle user input is key to many applications.
Overview of Reactive Forms
This section provides a basic reactive forms overview in the Angular framework. Reactive forms in Angular offer a model-driven approach to handle form inputs, the values of which change with respect to time. The state of a form at any given instant is managed by reactive forms using a fixed or inflexible approach. This implies that any change in the state of a form returns a new state.
This explicit approach sustains the form of state integrity between changes. Testing using reactive forms is straightforward because the data involved is consistent and predictable. Also, users accessing this data have permission to manipulate the data securely. But wait, ever wondered why they are called reactive forms?
This is because the form itself and each individual form control provide an Observable-based API, a very important feature of reactive forms. They operate on ‘observable streams’, that is, form inputs are made in the form of continuous streams of input values. These streams are beneficial as can be accessed synchronously and processed using common RxJs operators.
Looking to superstep theory and understand with the help of an Angular form example? Here is a cool Youtube video tutorial featuring an Angular reactive form example!
Some popular advantages of reactive forms include a less cluttered template, greater scalability, and the use of custom validators in Angular reactive forms validation. We will discuss these and more in detail later on in the article.
Why We Use Reactive Forms in Angular
Reactive forms are considered more powerful in comparison than Angular template-driven forms. This is due to several reasons, some of which are:
Immutability is the quality of not being able to ‘mutate’ or change. A mutation is precisely what reactive forms protect the form state from by providing an immutable or fixed data structure. For every change to the data model, observable operators return a new data model. This preserves the integrity of the data model between changes. This immutable approach towards managing the form state helps to keep the data model pure.
As explained earlier in the forms overview, reactive forms are built around observable streams. This helps to access input values in synchronously. Another vital role of observable streams is that they track changes in the form. All this makes reactive forms very predictable. Predictability, in turn, makes testing easier.
In reactive forms, the data flow is structured because reactive forms are leaded by the component class. This provides them with access directly to the FormControl instance after the creation of the link with the FormControlDirective. Each template is linked to the FormControl. Hence when a change occurs and a view update is required, the DOM is not re-rendered.
Scalability is a major highlight when it comes to the advantages of reactive forms in Angular. Reactive forms are synchronous and this quality makes scaling easier. This also increases their reusability and thus, they can be conveniently used with large-scale forms.
Greater testability is yet another fortunate fallout of synchronous access in reactive forms. Synchronous access to the form as well as the data models helps to test Angular apps easily before production. This is because reactive forms allow testing without rendering the UI.
Types of Forms in Angular
Forms in Angular are used to collect user input events from the view and validate the input from the user. They are also used to create a form model and a data model to update and help to track changes in the form. For handling user input, Forms in Angular are of two different types: Angular reactive forms and Angular template-driven forms. This article contains information about Angular reactive forms in detail.
Angular Reactive Form
The top feature of Angular reactive forms is direct, explicit access to the underlying forms object model. We briefly touched upon reactive form features like greater scalability, reusability, and testability in the reactive forms overview. These features of reactive forms provide an edge over template-driven forms.
Here is an API-summary for Angular reactive forms when you build your first Angular reactive form example.
Angular Template-driven Form
Template-driven forms used template directives to create and manipulate the underlying object model. However, their scalability and reusability are not as good as reactive forms. The main merit of template-driven forms, therefore, is their initial simplicity. This is useful for building small to medium-sized forms.
These approaches differ in many aspects and have their own set of benefits and drawbacks. Which approach you should choose depends on the kind of application you are building. For example, If your application has a significant usage of forms, then go for Angular reactive forms. However, if the form requirements of your application are basic, template-driven forms are the best fit.
Difference Between Template-driven And Reactive Forms in Angular
This section explores the main differences between template-driven and reactive forms in Angular. They differ on the following factors:
- Setup of Form Model;
- Data Model;
- Data Flow;
- Form Validation.
Setup of Form Model
In an Angular reactive form, the form model is defined directly in the component class. The FormControl instance is explicitly created and is linked to a specific form element in the view. This is done by the [formControl] directive with the use of an internal value accelerator. The form model is the source of truth.
In comparison, the form model in template-driven forms is implicit. The FormControl instance here is created and managed by the Ngmodel directive for a given form element. The template is the source of truth.
The data model is kept pure in Angular reactive forms owing to its immutable data structure. Detection of change is more efficient because only unique changes need to be updated. These data updates are in a reactive pattern, hence one can integrate with observable operators for data transmission.
Template-driven forms use a two-way binding system to update changes made on the template onto the data model. The use of two-way binding eliminates the tracking of unique changes as a result of which, change detection is less efficient.
As mentioned in earlier sections, the testability of Angular reactive forms is better and advantages of reactive forms in angular. The reason, again, is that the access to the form and the data model in an angular reactive form is synchronous. Thus, testing can be conducted without UI rendering.
Template-driven forms require one to have extensive knowledge of change detection processes and an understanding of how directives run on a cycle. Only then can one ensure that the elements are queried, tested, and changed immaculately.
Each form element in the view is directly linked to the form model in an angular reactive form. Updates to and from the view and the model are synchronous and hence independent of the UI rendering.
In contrast, each form element in the view is linked to a directive in template-driven forms. This directive then manages the form model internally.
Angular reactive forms validation is performed by means of functions. These functions are defined as the custom validators and receive control to validate.
In comparison to Angular reactive forms validation, validation in template-driven forms is bound to template directives.
More in-depth information on validation in an Angular reactive form is just a click away!
How to Use Reactive Forms in Angular
This section is a concise step-by-step Angular forms tutorial on how to apply Angular reactive forms in an application. But before going ahead with this Angular forms tutorial and using Angular reactive forms, one is required to install Node.js and create a local development environment.
Step 1 – Set up the project
This Angular forms tutorial requires you to start building from a default Angular project generated with @angular/cli. Set the styles of the project to CSS and add ReactiveFormsModule in the code editor.
Step 2 – Add a form to the component template
The logic is entirely declared in the component class in reactive forms. Hence, after step 2 of the Angular forms tutorial, you must have an Angular project ready with a component template using a form.
Step 3 – Build the component class
This step requires you to define the FormGroup in the component class and the individual FormControls inside it. The value provided when ‘newing’ a FormControl (if at all), serves as that particular field’s initial value.
Step 4 – Update the component class to use FormBuilder
For this step, you will need to visit app.component.ts again in the code editor and remove FormControl. This is followed by replacing FormGroup with FormBuilder. The purpose of this step is to drop all the ‘newing’ of the form group and form control.
Step 5 – Update the component class to use validators
Go to app.component.ts again in the code editor and add Validators. This step of the Angular forms tutorial involves adding the Validators class to your imports and use arrays and not simple string values to declare your form control.
Step 6 – Access form value and validity in the template
The value and validity of each FormControl’s value as well as the value and validity of the whole form group can be accessed in the template. This step requires you to revisit app.component.html and use *ngIf. In case the form values are not valid, feedback messages are displayed to the user.
Now that you know how to apply an Angular reactive form example, gear up and build your very first app with the Ignite UI for Angular CLI!
Reactive Forms Integration
Integrations in reactive forms enable independently designed applications to work together with the reactive forms. This increases the functionality of Angular forms. Developers at Infragistics created Angular components to benefit other developers using Angular. These integrations follow a model-driven approach for forms which makes it easier to handle form inputs.
One of the major plus points of using a reactive form integration is performance optimization. Well-designed integrations make it easier for developers to maneuver through different form components in less time and with more efficiency. Furthermore, the component development process at Infragistics provides complete transparency on Github. Hence, Angular developers can share ideas, issues, track progress, and much more only on Github.
Infragistics also ensures that as a developer using Angular, you do not have to install any third-party component that does not natively belong to Angular. You also get flexibility because of complete support with localization and globalization. Developers from any region or any locale can access these Angular components without any hassle.
Reactive forms are an essential component of any well-designed app. The reactive form integration in Ignite UI for Angular helps you build user-friendly web apps. Streamline your web app development process with 70+ Angular components, fast data grids, and pro features that aid a smooth user experience.