Search code examples
angulartypescriptangular-formsangular8

Angular 8: How to use formControlName with FormArray


How can I map formControlName to a specific formArray item?

I have no control over the server data and trying to create a form with a phone numbers array.

The form itself visually does not layout the phones side by side, and I want to be able to declare a phone's input control the same as I normally would with formGroup.

What I have so far is the below:

Controller:

const exampleData = {
                'name': 'John Doe',
                'phones': [
                    {
                        'type': 'home',
                        'number': '5555555'
                    },
                    {
                        'type': 'cell',
                        'number': '5555555'
                    }
                ]
            };

    this.form = this.fb.group({
         name:[],
         phones: this.fb.array([
             this.fb.group({
                 type: '',
                 number: []
             }),
             this.fb.group({
                 type: '',
                 number: []
             })
         ]),
     });

    this.form.patchValue(exampleData);

Template

<input type="text" formControlName="name">

<!--  This works but I need to loop -->
<div formArrayName="phones">
    <div *ngFor="let phone of form.get('phones').controls; let i = index">
        <div [formGroupName]="i">
            <label>Type: </label><input formControlName="type"/>
            <label>Number: </label><input formControlName="number"/>
        </div>
    </div>
</div>

<!--  How can I point to a phone directly? -->
<input type="text" formControlName="point to type home's number...with helper function or something...">

Looking to see if this is even possible?


Solution

  • Try this to get access to the formArray item:

      <div [formGroup]="form.get('phones').at(1)">
        <input type="text" formControlName="num">
      </div>
    

    Stackblitz