0

In my app I make a call and get an array that looks like:

[
  {
    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'
      }
    ]
  }
]

I need to build a form that displays all the projects and people as nested check boxes. So it would look like:

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

So it looks like I am going to need to nest together FormArrays inside Angular 2's ReactiveForms so that I can retrieve the IDs that have been selected. But the resources for FormArray are pretty limited and I haven't been able to get anything close to working. How can I template all of these via a form while displaying the name and tracking the IDs of the checked boxes?

What I am trying currently:

In my component

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

In my template

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

This is just to build a FormArray that shows the projects, and I keep getting an error that reads Cannot find control with unspecified name attribute. Note that buildFilter() is what I call after I get the array, and this should push the data into the FormArray.

Thanks.

user5021816
  • 167
  • 1
  • 2
  • 9
  • See http://stackoverflow.com/questions/36627573/angular2-form-controlgroup-who-hold-an-undefined-number-of-control and http://stackoverflow.com/questions/35652576/ngcontrol-with-ngfor-in-angular2 – Fiddles Nov 29 '16 at 01:30
  • 1
    I wasn't able to find a solution directly through those answers, but they let me here [http://stackoverflow.com/questions/34997128/angular-2-get-values-of-multiple-checked-checkboxes](http://stackoverflow.com/questions/34997128/angular-2-get-values-of-multiple-checked-checkboxes) and that solution using ngModel worked very well for what I needed. – user5021816 Nov 29 '16 at 19:53

0 Answers0