javascript - Angular 2 retrieve selected checkboxes -
i have checkbox (a customer may have many accessories):
customer.component.html:
<div class="checkbox" *ngfor="let accessory of accessories"> <label> <input type="checkbox" [(ngmodel)]="accessory.selected" (ngmodelchange)="oncheckboxchange(accessory)"> {{ accessory.name }} </label> </div>
customer.component.ts:
oncheckboxchange(accessory: any) { if (accessory.selected == true) { this.selectedaccessories.push(accessory); } else { let = this.selectedaccessories.indexof(accessory); if (i != -1) { this.selectedaccessories.splice(i, 1); } } }
i have method can save selected checkboxes in 1 array example:
customer: customer; accessories: any[]; selectedaccessories: any[]; ngoninit() { this.accessoryservice.get().subscribe( accessories => this.accessories = accessories ) if (this.routeparams.get('id')) { let id = this.routeparams.get('id'); this.getcustomer(id); } } getcustomer(id: number) { this.customerservice.getcustomer(id).subscribe( data => { this.selectedaccessories = data.customer.accessories this.customer = data.customer } ) }
it's working fine, when check object saved in database. don't know how can populate selected accessories checkboxes. tried compare arrays indexof() , map() without success
obs: object accessory have 2 attributes: id , name.
any appreciated
you binding checkboxes selected
attribute of object accessory
[(ngmodel)]="accessory.selected"
. means whenever check/uncheck checkbox accessory.selected
value updated. works other way around: if accessory.selected
value set, checkbox updated. can see idea demonstrated in following plunker: plunker - checkboxes
we first create array of accessories objects:
private accessories = [ {name: 'a', selected: false}, {name: 'b', selected: true} ];
note these accessories have name , selected value. value accessory b set true
. can see result when first loading page: checkbox accessory is unchecked (because of selected: false
), while checkbox accessory b checked (because of selected: true
). if check/uncheck checkbox, can see result of selected
property printed in console.
what means in code need set selected
property of objects in accessories
array appropriate value.
you go bit further this: listening oncheckboxchange
event keep track of array of selected accessories. leave out altogether , construct array when requested iterating on accessories , picking accessories out have selected: true
set.
Comments
Post a Comment