Middle
What is the difference between FormGroup and FormArray?
sobes.tech AI
Answer from AI
In Angular, FormGroup and FormArray are containers for managing forms, but they serve different purposes:
-
FormGroup is an object that groups together multiple controls (
FormControl) or other groups into a single logical structure. It is used when you have a fixed set of fields with named keys. -
FormArray is an array of controls or groups, where the number of elements can change dynamically. It is used for lists or repeating form elements.
Example:
const profileForm = new FormGroup({
firstName: new FormControl(''),
lastName: new FormControl(''),
aliases: new FormArray([
new FormControl('')
])
});
// Add a new alias
(profileForm.get('aliases') as FormArray).push(new FormControl(''));
Here, firstName and lastName are fixed fields, and aliases is a dynamic list.