Thibs
Thibs

Reputation: 8288

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?

Upvotes: 2

Views: 3350

Answers (2)

robert
robert

Reputation: 6152

Try this to get access to the formArray item:

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

Stackblitz

Upvotes: 3

Muhammed Albarmavi
Muhammed Albarmavi

Reputation: 24464

I solve this by run setValue to that component again this why any input by the same form control will update ,this become like two way data binding when we use ngModel where the data flow to the instant and other controls.

this the method will create the formGroup

getPhoneGroup() {
    const form = this.fb.group({
      type: '',
      num: []
    });

    const elm = form.get('num');
    elm.valueChanges.subscribe(val => {
      elm.setValue(val, { emitEvent: false })
    });

    return form;
  }

demo 🚀🚀

Upvotes: 2

Related Questions