简体   繁体   English

Angular 8:如何将 formControlName 与 FormArray 一起使用

[英]Angular 8: How to use formControlName with FormArray

How can I map formControlName to a specific formArray item?如何将 map formControlName设置为特定的formArray项?

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.表单本身在视觉上不会并排布置电话,我希望能够像通常使用 formGroup 一样声明电话的输入控件。

What I have so far is the below:到目前为止,我所拥有的是以下内容:

Controller: 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.我通过再次对那个组件运行setValue来解决这个问题,这就是为什么同一个表单控件的任何输入都会更新,当我们使用 ngModel 时,这就像两种方式的数据绑定,其中数据流向即时和其他控件。

this the method will create the formGroup这个方法将创建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:试试这个来访问 formArray 项目:

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

Stackblitz 堆栈闪电战

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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