我正在尝试获取客户端(id,name),但是我得到了一个空数组。
我正在使用此代码来获取我的客户端,以使用客户端ID和客户端名称填充NG-DROPDOWN。现在,我得到一个空数组。
this.clientService.getClients().subscribe((response: any) => {
for (let data of response) {
this.clientDropdownList.push({ '_id': response._id, 'name': response.name })
}
console.log(this.dropdownList)
}, error => {console.log("error :", error); }
);
服务:
getClients(): Observable<Client[]> {
return this.HttpClient.get<Client[]>('/api/clients');
}
HTML:
<ng-multiselect-dropdown class="customDropdown"
formControlName="client"
[placeholder]="'Select Client'"
[data]="[clientDropdownList]"
[(ngModel)]="selectedItems"
[settings]="dropdownSettings"
(onSelect)="onItemSelect($event)"
(onSelectAll)="onSelectAll($event)">
</ng-multiselect-dropdown>
我希望在clientDropdownList中有一个包含客户端ID和客户端名称的答案
答案 0 :(得分:0)
[data]="[clientDropDownList]"
。对于data
,您需要绑定不带括号的值。for... of
循环还可以,但是分配不正确,您正在设置数组的值,而不是数组中的项。模板代码:
<ng-multiselect-dropdown class="customDropdown"
formControlName="client"
[placeholder]="'Select Client'"
[data]="clientDropdownList" <!-- removed square brackets around the value -->
[(ngModel)]="selectedItems" <!-- where is this coming from -->
[settings]="dropdownSettings"
(onSelect)="onItemSelect($event)"
(onSelectAll)="onSelectAll($event)">
</ng-multiselect-dropdown>
组件代码
this.clientService.getClients().subscribe((response: any) => {
for (let data of response) {
// assign data. instead of response.
this.clientDropdownList.push({ '_id': data._id, 'name': data.name });
// or this seeing as the field names are identical
// this.clientDropdownList.push(data);
// you might even make a direct assignment but I am not sure if you are building the array from multiple sources
}
console.log(this.dropdownList);
}, error => console.log("error :", error)
)
答案 1 :(得分:0)
您应该删除[data]
绑定,并将clientDropdownList
绑定到下拉菜单。
像这样:
<ng-multiselect-dropdown class="customDropdown"
formControlName="client"
[placeholder]="'Select Client'"
[(ngModel)]="clientDropdownList"
[settings]="dropdownSettings"
(onSelect)="onItemSelect($event)"
(onSelectAll)="onSelectAll($event)">
</ng-multiselect-dropdown>