2
votes

H e l l o!

I have several checkboxes that I bind with ngModel inside ngFor, but if my markup is wrapped in <form> tag UI works unexpectedly. For example [checked]="team.original" and [disabled]="!group.internal" doesn't work line it should.

https://plnkr.co/edit/yxngdinXlHD1G9ITeGLT?p=preview

Thank you!

Edit:

For example do you see [checked]="team.original" and [disabled]="!group.internal" they don't work according to it's value. Also for 'Original' column I print actual value - 'false' but chackbox is checked.

1
What do you mean "doesn't work like it should"? What is the expected behavior and what do you get instead?AngularChef
O it is in the plnkr example. Do you see [checked]="team.original" and [disabled]="!group.internal" they don't work like they should if markup wrapped in <form> tag. Look at the object passed. Do you see one of the checkboxes print false but it is checked ? This is what I mean.Свободен Роб

1 Answers

0
votes

In forms, names need to be unique. So now in your form, it's not evaluated as two different teams as the name attribute is the same. Here usually you use the index to differentiate the name in iteration, so:

*ngFor="let team of group['teams']; let i=index"

and the name attribute

name="read{{i}}"

You have one further issue, since the teams are in two different groups and each team has the index 0 in their separate array. So if using the above, you would end up with the same name attribute.

read{{i}} would end up to be read0 which still doesn't solve your issue, since it would be evaluated as one and the same form name. Therefore you need to use TWO indexes, both for the top level iteration and the nested iteration:

<div *ngFor="let group of groups; let j=index">

and

<tr *ngFor="let team of group['teams']; let i=index">

and mark your name attributes:

name="read{{j}}{{i}}"

NOW all items in your form have unique names, so the result of your form values would look like this:

{
  "read00": true,
  "download00": true,
  "original00": false,
  "read10": true,
  "download10": true,
  "original10": true,
  "contribute10": true,
  "manage10": false
}

This is just how forms work. All names must be unique.

Here's your forked Plunker