The Basics - Form Groups,
Form Controls & From Arrays
How to learn about Angular Forms
A typical approach developers create forms is to place input elements in the DOM without thinking too
much about the output object, as it can be transformed anyhow. However, for a basic understanding of
Angular Forms, we should take a step back and start with the output that represents all the data the
user has typed into the form.
Relating the form output to the form elements
Consider your form output will generate a JSON-object:
{
"customerNumber":"C1004234",
"phoneNumbers":[
"0041791112233",
"0041442223344"
],
"address":{
"street":"Angularstreet",
"streetNumber":"104",
"postalCode":"8000",
"city":"Zürich"
}
}
Relating the form output to the form elements
- If the field represents an object, use FormGroup
- If the field represents a list, use FormArray
- If the field represents a single value or is a value of a FormArray, use FormControl
- The root itself is always a FormGroup and has to be assigned to the form-tag
Relating the form output to the form elements
Therefore, our JSON transforms to:
{ // <-- FormGroup (always goes on the form-tag)
"customerNumber":"C1004234", // <-- FormControl
"phoneNumbers":[ // <-- FormArray
"0041791112233", // <-- FormControl
"0041442223344" // <-- FormControl
],
"address":{ // <-- FormGroup
"street":"Angularstreet", // <-- FormControl
"streetNumber":"104", // <-- FormControl
"postalCode":"8000", // <-- FormControl
"city":"Zürich" // <-- FormControl
}
}
AbstractControl
In Angular, each input field or group of fields, including the form itself is represented by a subtype of AbstractControl. An AbstractControl provides:
- State
- valid / invalid
- dirty / pristine
- touched
- errors
- Value
Subtypes of AbstractControl
- FormControl
- FormGroup
- FormArray
FormControl
- A FormControl represents a single input field
FormGroup
- FormGroups manage multiple FormControls
- Used for clustering values together, which belong together, e.g. an address
- The form itself is always represented by a FormGroup
FormArray
- FormArrays manage multiple FormControls
- Used for a series of input fields of same kind, e.g.
- phone number input fields
- ordering of calling sequence