We can duplicate form controls or form groups using a form array.
- Remember to setup a div with a form group when added to the component code.
- build a function that creates the formgroups:
buildFields(): FormGroup {
return this.fb.group({
field1: '1',
field2: '2'
});
}
Replace the way we were building the fields inside the formgroup with calling the function:
this.customerForm = this.fb.group({
fields: this.buildFields()
});
Create FormArray and replace the above code with:
this.customerForm = this.fb.group({
fields: this.fb.array([this.buildFields()])
});
Define a getter to allow the data to be retrieved:
get fields(): FormArray{
return this.customerForm.get('fields');
}
where fields is the name of the form item on the html. We need to add a div..
<[formGroupName]="i">