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"
Found the problem. It is getting confused inside the
<form>
. Remove the<form>
and you can simplify the code to this.It should work