角嵌套形式

时间:2019-12-02 22:11:40

标签: angular angular-reactive-forms

我正在尝试使用嵌套的反应形式。

当我尝试显示嵌套数组时,出现错误“找不到具有路径的控件:'联系人->电话-> 0->数字'”

这是我的有效载荷

     {
          "_id": "5ddb9fa8545eb65b5b28a471",
          "contact": {
            "addressLocation": {
              "apartment": "34",
              "balding": "43",
              "street": "some street"
            },
            "iconImage": "",
            "mail": "noman@gmail.com",
            "phone": [
              {
                "name": "ABC",
                "number": "0548888888"
              }
            ]
          },
          "content": "some content",
          "title": "some title",
          "type": "regular",
          "userId": "5d96545b7d84d2201abc879",
          "updatedAt": "2019-11-25T09:32:24.886Z"
        }

这是我的HTML

      <form [formGroup]="formC" (ngSubmit)="onSubmit()">

            <div [formGroupName]="'contact'">

                <div [formGroupName]="'addressLocation'">
                    <input type="text" class="form-control" [formControlName]="'apartment'">
                    <input type="text" class="form-control" [formControlName]="'balding'" >
                    <input type="text" class="form-control" [formControlName]="'street'">
      </div>

                    <input type="text" class="form-control" [formControlName]="'iconImage'" >
                    <input type="text" class="form-control" [formControlName]="'mail'">


                    <div [formArrayName]="'phone'">
                        <ul class="subjectList">
                            <li *ngFor="let item of phoneFormArray.controls; let i = index">

                                <div [formGroupName]="i">
                                    <input type="text" class="form-control" [formControlName]="'name'">
                                    <input type="text" class="form-control" [formControlName]="'number'">
              </div>
                            </li>
                        </ul>
                    </div>
                </div>

        </form>

And here it a live Demo

我想念什么?

谢谢

1 个答案:

答案 0 :(得分:1)

使用表单数组时,您需要通过实际创建表单组并将其推入数组来设置其值:

  constructor(public fb: FormBuilder) {
     this.formC.patchValue(this.data);
     this.data.contact.phone.forEach(p => this.addPhone(p))
  }

  addPhone(p) {
    const fg = this.blankPhoneFg
    fg.setValue(p)
    this.phoneFormArray.push(fg)
  }

  get blankPhoneFg() {
    return this.fb.group({
      name: ['', Validators.required],
      number: ['', Validators.required],
    })
  }

还将数组初始化为空:

phone: this.fb.array([]),

如果要使用一个空组初始化它,则需要确保将一个实际组而不是一个对象放在其中:

phone: this.fb.array([this.blankPhoneFg]),

固定的闪电战:https://stackblitz.com/edit/nested-forms-angular-wool3t?file=src/app/app.component.ts

您可能需要执行类似的操作,例如在最后添加一个空的组,或者如果没有电话或其他任何内容,则无论您需要什么