Using Reactive Patterns in Angular Forms
Learn how to create reactive forms and interact with them in Angular.
We'll cover the following
We will dive deeper into an alternative approach offered by the Angular framework for forms creation, i.e., reactive forms. Reactive forms, as the name implies, provide access to web forms in a reactive manner. They are built with reactivity in mind, where input controls and their values can be manipulated using observable streams. They also maintain an immutable state of form data, making them easier to test because we can be sure that the state of the form can be modified explicitly and consistently.
Reactive forms have a programmatic approach to creating form elements and setting up validation rules. We set everything up in the component class and merely point out our created artifacts in the template.
The Angular key classes involved in this approach are the following:
FormControl
: Represents an individual form control, such as an<input>
elementFormGroup
: Represents a collection of form controls. The<form>
element is the topmostFormGroup
in the hierarchy of a reactive form.FormArray
: Represents a collection of form controls, just likeFormGroup
, but can be modified at runtime. For example, we can add or removeFormControl
objects dynamically as needed.
All these classes are available from the @angular/forms
npm package. The FormControl
and FormGroup
classes inherit from AbstractControl
, which contains a lot of interesting properties. We can use these properties to render the UI differently based on what status a particular control or group has. We might want to differentiate UI-wise between a form we have never interacted with and one we have. It could also be interesting to know whether we have interacted with a particular control. As we can imagine, there are many scenarios where it is interesting to know a specific status. We will explore all these properties using the FormControl
and FormGroup
classes.
Next, we will explore how to work with reactive forms in Angular using our component for creating new products.
Interacting with reactive forms
The Angular application we have built contains a component to add new products for our e-shop. When we built the component previously, we might have noticed that the name and price input controls were not cleared upon creating a product. Implementing such functionality would be complex because we would need to access the native <input>
elements inside the component class. However, Angular forms provide a helpful and convenient API that we can use to accomplish this task. We will learn how to use reactive forms by integrating them into the product create component:
Open the
products.module.ts
file and importReactiveFormsModule
from the@angular/forms
npm package:
Get hands-on with 1200+ tech skills courses.