0

在我的应用程序中,我拨打电话并获得一个如下所示的数组:

[
  {
    project: 'One',
    id: 'a123',
    people: [
      {
        name: 'John'
        id: 'axyz'
      },
      {
        name: 'Jane'
        id: 'bxyz'
      }
    ]
  },
  {
    project: 'Two',
    id: 'b123',
    people: [
      {
        name: 'Smith'
        id: 'cxyz'
      },
      {
        name: 'Jones'
        id: 'dxyz'
      }
    ]
  }
]

我需要构建一个表单,将所有项目和人员显示为嵌套复选框。所以它看起来像:

-One
  -John
  -Jane
-Two
  -Smith
  -Jones

所以看起来我需要将 FormArrays 嵌套在 Angular 2 的 ReactiveForms 中,以便我可以检索已选择的 ID。但是 FormArray 的资源非常有限,我还没有得到任何接近工作的东西。如何在显示名称和跟踪复选框的 ID 的同时通过表单对所有这些进行模板化?

我目前正在尝试什么:

在我的组件中

faParties: FormArray;
formFilter: FormGroup;

ngOnInit() {
    this.formFilter = this._fb.group({
        parties: this.buildFA()
    });
}

buildFA(): FormArray {
    this.faParties = this._fb.array([
        this.buildFAParties
    ]);
    return this.faParties
}

buildFAParties(name): FormGroup {
    let tName = name;
    if (tName == null || tName == 'undefined') {
        tName = 'name';
    }
    return this._fb.group({
        name: ''
    });
}

buildFilter() {
    for (let i = 0; i < this.parties.length; i++) {
        this.faParties.push(this.buildFAParties(this.parties[0].name))
    }        
}

在我的模板中

<form [formGroup]="formFilter" class="inline-form">
  <div *ngFor="let party of faParties.controls; let i=index" [formGroupName]="i">
    <input class="check" formControlName="name" id="p{{ i }}" type="checkbox" checked>
    <label class="check" htmlFor="p{{ i }}"><div><span class="lnr lnr-check"></span></div><span>here</span></label>
  </div>
</form>

这只是为了构建一个显示项目的 FormArray,并且我不断收到一个错误,显示为Cannot find control with unspecified name attribute. 请注意,这buildFilter()是我在获取数组后调用的内容,这应该将数据推送到 FormArray。

谢谢。

4

0 回答 0