我有這個複選框(一個客戶可能有許多配件):角2個檢索選擇複選框
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 i = this.selectedAccessories.indexOf(accessory);
if (i != -1) {
this.selectedAccessories.splice(i, 1);
}
}
}
我有一種方法可以將選中的複選框保存在一個數組中,例如:
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
}
)
}
它工作正常,當我檢查對象保存在數據庫中。 但我不知道如何將選定的配件填充回覆選框。我試圖用indexOf()和map()比較數組,但沒有成功
Obs:對象附件只有2個屬性:id和name。
任何幫助,將不勝感激
你想從數據庫檢索數據時檢查您的複選框? –