
Reactive forms
The other type of form that Angular supports is called reactive forms. Reactive forms start with a model that is constructed in a component class. With this approach, we use the form builder API to create a form in code and associate it with a model.
Given the minimal code we have to write to get template-driven forms working, why and when should we consider using reactive forms? There are several situations in which we might want to use them. These include cases where we want to take programmatic control of creating the form. This is especially beneficial, as we will see, when we are trying to create form controls dynamically based on data we are retrieving from the server.
If our validation gets complicated, it is often easier to handle it in code. Using reactive forms, we can keep this complicated logic out of the HTML template, making the template syntax simpler.
Another significant advantage of reactive forms is that they make unit-testing the form possible, which is not the case with template-driven forms. We can simply instantiate our form controls in our tests and then test them outside the markup on our page.
Reactive forms use three new form directives that we haven't discussed before: FormGroup, FormControl, and FormArray. These directives allow the form object that is constructed in code to be tied directly to the HTML markup in the template. The form controls that are created in the component class are then directly available in the form itself. Technically speaking, this means that we don't need to use ngModel (which is integral to template-driven forms) with reactive forms (although it can be used). The overall approach is a cleaner and less cluttered template with more focus on the code that drives the form. Let's get started with building a reactive form.