网站搜索

typescript - Angular 8:如何在 FormArray 中使用 formControlName


我如何将 formControlName 映射到特定的 formArray 项?

我无法控制服务器数据,并且正在尝试创建一个包含电话号码数组的表单。

表单本身在视觉上不会将手机并排显示,我希望能够像通常使用 formGroup 那样声明手机的输入控件。

到目前为止,我已有如下内容:

控制器:

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);

模板

<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...">

想看看这是否可能吗?

答案#1

尝试这个来访问 formArray 项:

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

Stackblitz

答案#2

我通过再次对该组件运行 setValue 来解决这个问题,这样同一表单控件的任何输入都会更新,这就像使用 ngModel 时的双向数据绑定,数据会流向实例和其他控件。

这个方法将创建 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;
  }

演示 🚀🚀