In the previous post, we discovered the template-driven approach for building forms. Here is a link to the post: Building Forms The Angular Way.
In this tutorial, we will discover how to build forms using the reactive approach.
In contrast to template-driven forms, reactive forms are entirely controlled through the logic (ts component). Also, they are more robust and testable.
๐ฉ๐จโ๐ณRecipe
๐ Head to app.module, and import the ReactiveForms module from angular/forms, and equally add it to the imports array.
Doing this gives us access to the following directives, formGroup,
formControlName, formControl, formBuilder and formArray.
Quick recap: form-controls represent a single input, and a formGroup is a collection of formControls.
The FormGroup object has the following properties errors, dirty, valid, value. The errors hold the validation errors, the touch value is boolean indicating if an input has received focused, the dirty property is equally boolean, it indicates if an input has been filled.
๐ Head to your logic and import formGroup, formControl from angular/forms
In our logic, we will create a studentForm property to keep track of students. Create it, then define its type to be of type formGroup.
Then in the ngOnInit method, we will initialize it to a new FormGroup instance, and define its form controls. That is the email and name.
๐ Head to your view, and add the following code.
In the template, we use property binding to bind the form, to our studentForm property.
For each input, we attribute the formControlName directive, which we assign to the form control defined in our logic.
๐ Head to your browser. Initially, you should see something like this
Now, when we modify our form, we realize the formGroup properties change.
๐๐๐พCongratulations. You have just built a form using the reactive approach.
Top comments (0)