Binding ngModel to Dynamic Checkbox List : Angular 2 / Typescript
I have a code similar to yours (ngFor
over all of the possible checkboxes, some of them should be checked, changes are to be saved in some data structure we are not iterating over), and here's what I come up with:
<md-checkbox
*ngFor="let some of availableSomes"
name="{{ some }}"
checked="{{ data.somes && -1 !== this.data.somes.indexOf(some) ? 'checked' : '' }}"
(change)="updateSome($event)">
{{ some }}
</md-checkbox>
Here's updateSome
:
updateSome(event) {
if (-1 !== this.availableSkills.indexOf(event.source.name)) {
if (event.checked) {
this.data.somes.push(event.source.name);
} else {
this.data.somes.splice(this.data.somes.indexOf(event.source.name), 1);
}
}
}
Also, I believe it should be event.target
, but it's event.source
due to material. Kind of clumsy solution, but I think it will help you figure out how can you achieve what you want
Based on НЛО answer above I was able to figure out the solution to my question. Thank you НЛО.
<div class="form-group">
<label for="timeslots">Select Timeslots Available for Rent *</label>
<div *ngIf="dbtimeslots">
<span *ngFor="let timeslot of dbtimeslots" class="checkbox">
<label>
<input type="checkbox" value="{{timeslot.id}}" name="{{timeslot.id}}" [checked]="(facility.timeslotids && (-1 !== facility.timeslotids.indexOf(timeslot.id)) ? 'checked' : '')" (change) ="updateSelectedTimeslots($event)" />{{timeslot.timeslotname}}
</label>
</span>
</div>
</div>
Then the function on the component:
updateSelectedTimeslots(event) {
if (event.target.checked) {
if (this.facility.timeslotids.indexOf(parseInt(event.target.name)) < 0) {
this.facility.timeslotids.push(parseInt(event.target.name));
}
} else {
if (this.facility.timeslotids.indexOf(parseInt(event.target.name)) > -1)
{
this.facility.timeslotids.splice(this.facility.timeslotids.indexOf(parseInt(event.target.name)), 1);
}
}
//console.log("TimeslotIDs: ", this.facility.timeslotids);
}