How would you build a dynamic form with a variable number of fields, such as a list of phone numbers, using reactive forms?
Short answer
You use a FormArray, which holds a dynamic list of form controls, letting you add or remove entries at runtime, such as letting a user add as many phone numbers as they need, while Angular keeps track of the validity of the entire array of fields.
Advertisement
AModel answer
You use a FormArray, which holds a dynamic list of form controls, letting you add or remove entries at runtime, such as letting a user add as many phone numbers as they need, while Angular keeps track of the validity of the entire array of fields.
form = new FormGroup({
phoneNumbers: new FormArray([new FormControl('')])
});
addPhoneNumber() {
(this.form.get('phoneNumbers') as FormArray).push(new FormControl(''));
}Real-world example
A job application form lets a user add multiple previous employers dynamically, using a FormArray to manage however many entries the user decides to add, without needing to predefine a fixed maximum number of fields.
Likely follow-ups
- How do you remove a specific entry from a FormArray at runtime?
- How would you validate that a FormArray has at least one entry filled in?
Related topics