Angular
Intro to Reactive Forms in Angular - Make Forms Dynamic
  •  

Demo: FormArray with FormControls in the Component

PRO

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:

  1. Import FormArray from @angular/forms
  2. 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('')])
  3. 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; }
  4. Add a new method to be able to add to the phoneNumbers FormArray. addPhoneNumber() { this.phoneNumbers.push(this.fb.control(''); }
  5. Optionally, you can refactor a bit by extracting the two instances of this.fb.control('') into a method.