I am attempting to create a form for a user that will allow one to may phone numbers to be associated with the user. Is this possible with the current implementation of reactive forms? For example, I would want the below form to accept potentially many phone numbers. My front end implementation would show the phone number field, and would have a button that would allow for an additional phone number field to be added.
userForm = new FormGroup({
firstName: new FormControl('', Validators.required),
lastName: new FormControl('', Validators.required),
phoneNumber: new FormControl('', Validators.required)
});
My hack solution would be
userForm = new FormGroup({
firstName: new FormControl('', Validators.required),
lastName: new FormControl('', Validators.required),
phoneNumber: new FormControl('', Validators.required),
phoneNumber1: new FormControl(),
phoneNumber2: new FormControl(),
phoneNumber3: new FormControl(),
phoneNumber4: new FormControl()
});
I could suppress the additional phone fields until the add an additional phone number button is clicked.
What you want to use is a
FormArray
where you can add new Form Controls dynamically:And then your template:
Demo