0

I am aware of both FormArray from reactive forms and the method of objects in an array or map as described in this question. Normally I would use the former, and if absolutely necessary the latter - but I would like to know if it is possible with just an array of boolean values.

template

<div>
  <h2>Hello {{name}}</h2>
</div>
<input type="checkbox" *ngFor="let item of items; let i = index;" [(ngModel)]="items[i]"/>

component

@Component({
  selector: 'my-app',
  template: `...`,
})
export class App {
  name:string;
  items = [false, false, true];
  constructor() {
    this.name = `Angular! v${VERSION.full}`
  }
}

With the files as above, clicking the first checkbox will change the value of other checkboxes. Is there a mistake I have made, or is this not possible in Angular?

Gif showing the incorrect behaviour:

Gif showing the incorrect behaviour

Live example on Plunker

0mpurdy
  • 3,198
  • 1
  • 19
  • 28

1 Answers1

2

The ngFor must be a level up in order to avoid the reference issue.

<div *ngFor="let item of items; let i = index;" >
     <input type="checkbox" [(ngModel)]="items[i]"/>
</div>

Updated Plunker

Aravind
  • 40,391
  • 16
  • 91
  • 110
  • Having a look at the plunker I get a wrong behaviour if I initially click on the first checkbox. Any idea where this might come from? It seems that the initial values are taken correctly. – JDC Mar 06 '18 at 10:56
  • Thanks @JDC I'll look into it – Aravind Mar 06 '18 at 16:48