Reputation: 4480
I am new to angular and am stuck at this pretty simple problem. I am getting data from a webservice to show a couple of checkboxes. I need a way to get the value of all of the checkboxes selected by the user. I am using material theme.
<span *ngFor="let x of maintainanceTypeList">
<md-checkbox
name="{{x.maintenancetype}}"
value="{{x.maintenancetype}}"
[formControl]="CreateSocietyForm.controls['checkMaintainanceType']">
{{x.maintenancetype}}
</md-checkbox>
</span>
Upvotes: 5
Views: 23085
Reputation: 245
Instead of e.checked
you can use the following:
Working example
HTML
<input class="form-check-input" type="checkbox" (change)="selectBadge($event, badge._id)">
Typescript
selectBadge (e, id) {
if (e.target.checked) {
this.product.badges.push(id);
} else {
this.product.badges.splice(this.product.badges.indexOf(id), 1);
}
}
Upvotes: 11
Reputation: 13297
You can add a change
event to md-checkbox
and pass the object to a function. Maintain an array
that keep track of which ones got checked
and unchecked
and update the array according to that.
html:
<span *ngFor="let x of maintainanceTypeList">
<md-checkbox
name="{{x.maintenancetype}}"
value="{{x.maintenancetype}}"
(change)="change($event, x)">
{{x.maintenancetype}}
</md-checkbox>
</span>
<p> Selected value: {{selectedValue | json}} </p>
component.ts:
export class SelectFormExample {
selectedValue = [];
maintainanceTypeList = [
{maintenancetype: 'Steak'},
{maintenancetype: 'Pizza'},
{maintenancetype: 'Tacos'}
];
change(e, type){
console.log(e.checked);
console.log(type);
if(e.checked){
this.selectedValue.push(type);
}
else{
let updateItem = this.selectedValue.find(this.findIndexToUpdate, type.maintenancetype));
let index = this.selectedValue.indexOf(updateItem);
this.selectedValue.splice(index, 1);
}
}
findIndexToUpdate(type) {
return type.maintenancetype === this;
}
}
Upvotes: 9