BlueM
BlueM

Reputation: 3851

Angular2: ControlGroup inside ControlArray

I’m having a hard time figuring out how to iterate over a ControlArray that contains Controlgroups in a template. In TypeScript, so far I have created the ControlArray, and by iterating over data received from a remote service, I added a few ControlGroups to the array. Everything fine up to this point, and I can see the expected data structure in the console.

In the template, I have this:

<div *ngFor="#c of categories.controls">
    <div ngControlGroup="c">
    </div>
</div>

... where categories is the ControlArray (which holds an array of ControlGroups in its controls property). When I leave out the inner <div>, I don’t get an error, which suggests that Angular agrees with me that categories.controls is indeed an array. But as soon as I re-add the inner <div> (where I expect the local variable c to be one of the objects in the array), I get an exception with message “Cannot find control 'c' in [c in ]”. Also, I tried various other syntactical approaches, but none of them worked. In addition to a “Cannot find control …” method I also got “Cannot find a differ supporting object …”, but that didn’t take me any further.

Any hints regarding what I’m doing wrong?

Upvotes: 2

Views: 2703

Answers (3)

jmreidy
jmreidy

Reputation: 471

ngControlGroup is defining a new control group. If I understand your question correctly, you want to actually be editing items within a control group inside a control array. Check out this plnkr: https://plnkr.co/edit/3gM2TuMGBW13HNATUcCO

<div *ngFor="#c of categories.controls; #i = index">
      Control group {{i}}:
    <div>
        <input type="text" class="form-control m-b" [ngFormControl]="c.controls.title"/>
        <input type="text" class="form-control m-b" [ngFormControl]="c.controls.id"/>
      </div>  
    </div>

Upvotes: 1

Pardeep Jain
Pardeep Jain

Reputation: 86740

Error is resolved by changing

ngControlGroup="c"

into

attr.ngControlGroup="c"

Because by assigning c to ngControlGroup you are just assigning the value instead of any binding. but strange why [ngControlGroup] still produces some error.apart from these here is working example https://plnkr.co/edit/Yw21a1aSivNg4G6gYkhF?p=preview

Upvotes: 1

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657348

One error is

ngControlGroup="c"

which doesn't do any binding. It passes the literal c to ngControlGroup. It should be:

[ngControlGroup]="c"

The errors that are still produced after this fix seem because there are no controls.

Upvotes: 1

Related Questions