简体   繁体   中英

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?

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

Try this to get access to the formArray item:

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

Stackblitz

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM