我正在尝试创建多个 ng-select,由此我从同一个数组中过滤出每个 ng-select,即它是一个具有不同选项的数组,用于对所有数组使用一个列表,而不是绑定多个数组。
我在测试的角度组件中有以下变量:
sites: Dropdown[];
dropdownValues: Dropdown[];
Dropdown 是一个包含 3 个变量的类:id、text、group。上面的数组是通过从 API 调用中获取不同项目的列表而写入的,如下所示:
this.configService.getDropdowns.subscribe(result => {
this.sites = result.filter(dd => dd.group == 'Site');
this.dropdownValues = result;
});
在上面的代码中,我使用 this.sites= 示例来测试过滤数组以测试填充下拉列表,这在设置 ng-select [items]="sites" 时工作正常。但是我不想为页面上的每个下拉列表编写局部变量和过滤器行,所以我尝试使用一个函数:
getDropdowns(group: string): Dropdown[] {
if(this.dropdownValues == null) return [];
else return this.dropdownValues.filter(dd => dd.group == group);
}
然后我将 [items] 更改为:[items]="getDropdowns('Department')"。
这确实有效,现在确实列出了正确的项目,但由于某种原因,我无法再实际选择它们,所以我认为这样做在某种程度上破坏了绑定。我应该有更好的方法吗?
ng-select 示例在我的 html 上:
<ng-select [items]="sites" bindLabel="text" bindValue="id" [multiple]="true" [closeOnSelect]="true" [(ngModel)]="filters.siteIds" name="cboSite" ></ng-select> // works great
<ng-select [items]="getDropdowns('Department')" bindLabel="text" bindValue="id" [multiple]="true" [closeOnSelect]="true" [(ngModel)]="filters.departmentIds" name="cboDepartment" ></ng-select> // shows options correctly but cannot select