Form Controls and Form Groups
In Angular, Forms are mainly used to handle user inputs. They are a crucial part of any web application and can be implemented using either template-driven or reactive forms model. In this tutorial, we will focus more on Reactive Forms and keenly delve into 'Form Controls' and 'Form Groups'.
What are Form Controls and Form Groups?
In Angular's Reactive Forms, a FormControl
represents a single form control, like an input field. It allows you to track the value and the validation status of the individual input field.
On the other hand, a FormGroup
is a collection of FormControl
instances. It aggregates the values of each child FormControl
into one object, with each control name as the key. It calculates its status by reducing the status values of its child controls.
Creating Form Controls
To create a FormControl
, you need to import FormControl
from @angular/forms
and then instantiate a new FormControl
.
import { FormControl } from '@angular/forms';
name = new FormControl('');
In the above example, an instance of FormControl
is created. This instance is associated with an HTML input field in the component's template.
Setting and Updating Form Control Values
The FormControl
class has handy methods that allow you to update, retrieve or reset the value of the form control.
- setValue(): This method allows you to set a new value for the form control.
name.setValue('John Doe');
- patchValue(): This method is used to update the value of the form control.
name.patchValue('John');
- reset(): This method resets the value of the form control to an initial state.
name.reset();
Creating Form Groups
As earlier stated, FormGroup
is a group of form controls. We create a FormGroup
by instantiating a new FormGroup
object and passing in an object of form controls.
import { FormGroup, FormControl } from '@angular/forms';
profileForm = new FormGroup({
firstName: new FormControl(''),
lastName: new FormControl(''),
});
In the above example, a new FormGroup
instance is created with two form controls.
Accessing Form Group Values
To access the values of the controls in the form group, you use the value
property of the FormGroup
instance.
console.log(this.profileForm.value);
Conclusion
In conclusion, the powerful FormControl
and FormGroup
classes provide a way to define form controls and groups, set and update their values, and check their validation status. These form classes are fundamental in implementing reactive forms in Angular. They offer a more flexible, scalable, and reusable way of creating forms, as compared to the template-driven approach.
In the next tutorial, we will dig deeper into more advanced features of Angular Reactive Forms, including form builders and form arrays. Stay tuned!