Checkbox not applying check on load when using *ngFor in Angular 2

1k views Asked by At

I have a dynamic list of checkBoxes that are built using *ngFor. The model updates just fine whenever I manually check the boxes, but if the model is preset to have a checked box, the box will not be checked on load.

<form action="demo_form.asp" method="get">
  <div *ngFor="let d of data; let in=index; trackBy:trackByIndex">
    <input type="checkbox" 
           name="value" 
           [(ngModel)]="data[in].value"
           [(checked)]="data[in].value" 
           (change)="checkChanged($event)"/>
    {{d.text}}
  </div>      
</form>

I've learned you need to us trackBy when using primitives within an ngFor so here is my trackByIndex:

public trackByIndex(index: number, data: TextValuePair): any {
   return index;
}

Here is the data:

public data = [{ text: "Human", value: true }, { text: "Dog", value: false }]

I need the checkboxes to be checked on load if an object in the list has value set to "true"

1

There are 1 answers

0
ed-tester On BEST ANSWER

Found the problem. It is getting confused inside the <form>. Remove the <form> and you can simplify the code to this.

  <div *ngFor="let d of data">
    <input type="checkbox" 
           name="data" 
           value="{{d.text}}"
           [(ngModel)]="d.value"
           (change)="checkChanged($event)"/>
    {{d.text}}
  </div>

It should work