Dynamic form arrays
Note that the phones
property is an array, potentially allowing for many inputs. We can implement this by building a FormArray
with the this.formBuilder.array
function. We also define several helper functions to make it easier to build the FormArray
:
buildPhoneFormControl
helps to buildFormGroup
objects of individual entries.buildPhoneArray
creates as manyFormGroup
objects as needed, or if the form is empty, it creates an empty entry.addPhone
adds a new emptyFromGroup
object to theFormArray
.get phonesArray()
is a convenient property to get thephones
control from the form.
Let’s see how the implementation comes together:
src/app/user/profile/profile.component.ts
...
phones: this.formBuilder.array(this.buildPhoneArray(user?.phones || [])),
...
private buildPhoneArray(phones: IPhone[]) {
const groups = []
if (phones?.length === 0) {
groups.push(this.buildPhoneFormControl(1))
} else {
...