In this demo, we'll add a FormArray to our form that will contain FormControls. There are a few steps we must take in the component:
- Import FormArray from @angular/forms
- Inside initializeForm(), we'll add a Form Array called phoneNumbers that starts off as one empty FormControl, like so:
phoneNumbers: this.fb.array([this.fb.control('')])
- Add a component level getter for phoneNumbers for reuse. We'll need to type it as a FormArray because it would otherwise return the base class of AbstractControl.
get phoneNumbers(): FormArray { return this.regForm.get('phoneNumbers') as FormArray; }
- Add a new method to be able to add to the phoneNumbers FormArray.
addPhoneNumber() { this.phoneNumbers.push(this.fb.control(''); }
- Optionally, you can refactor a bit by extracting the two instances of
this.fb.control('')
into a method.