我正在尝试修补ng-select下拉列表中的多个选定项。我没有指定任何bindValue,所以这些项应该通过object进行绑定(在https://www.npmjs.com/package/@ng-select/ng-select中指定)
但在尝试执行此操作时,项不会根据对象而是根据显示的标签进行选择。而且,只有第一个标签会被选中。
示例: app.component.html
<form [formGroup]="group">
<div class="form-group" formGroupName="school">
<ng-select labelForId="school" placeholder="Select school" [items]="schools" formControlName="code"
bindLabel="displayLabel" multiple="true" groupBy="city">
</ng-select>
</div>
</form>app.component.ts
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, FormControl, Validators } from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
group: FormGroup;
schools = [];
constructor(private fb: FormBuilder) { }
ngOnInit() {
this.initSchools();
const formModel = {
school: new FormGroup({
code: new FormControl(null, Validators.required)
})
}
this.group = this.fb.group(formModel);
this.group.patchValue({
school: {
code:
[
{
schoolId: 'SC003',
displayLabel: 'Test-3 school',
city: "City1"
},
{
schoolId: 'SC005',
displayLabel: 'Test-3 school',
city: "City5"
}
]
}
});
}
initSchools() {
this.schools.push(
{
schoolId: 'SC001',
displayLabel: 'Test-1 school',
city: "City1"
},
{
schoolId: 'SC002',
displayLabel: 'Test-2 school',
city: "City2"
},
{
schoolId: 'SC003',
displayLabel: 'Test-3 school',
city: "City3"
},
{
schoolId: 'SC004',
displayLabel: 'Test-4 school',
city: "City4"
},
{
schoolId: 'SC005',
displayLabel: 'Test-3 school',
city: "City5"
}
);
}
}在上面的示例中,只有item的对象
{
schoolId: 'SC003',
displayLabel: 'Test-3 school',
city: "City1"
},被选中,
而下面的项目并不
{
schoolId: 'SC005',
displayLabel: 'Test-3 school',
city: "City5"
}应该怎么做才能让两个项目都在下拉列表中被选中(提供唯一的对象)。这里有没有遗漏什么。任何其他实现这一目标的方法。
在这里运行示例:https://stackblitz.com/edit/angular-szel64?file=src%2Fapp%2Fapp.component.ts
发布于 2020-02-12 18:21:20
我发现对于ng-select有一个compareWith选项,它允许您定义一个函数来比较对象。使用此选项,您可以绑定对象,并根据compareWith选项提供的功能将其选中。
下面是我的更改,以防任何人遇到同样的问题
app.component.html
<form [formGroup]="group">
<div class="form-group" formGroupName="school">
<ng-select labelForId="school" placeholder="Select school" [items]="schools" formControlName="code"
bindLabel="displayLabel" multiple="true" groupBy="city"
[compareWith]="compareFunction">
</ng-select>
</div>
</form>app.component.ts
...
compareFunction(item, selected) {
// any logic to compare the objects and return true or false
return item.schoolId === selected.schoolId
}
...https://stackoverflow.com/questions/60111829
复制相似问题