如何防止在 ng-select 中跨多个选择选择选择的值



我有两个下拉菜单,它们从同一个数组中获取数据。如果我在第一个下拉列表中选择一个选项,则该值在第二个下拉列表中应该不可用,反之亦然。

我正在使用 ng-select,但我可以看到与我的问题相关的任何内容。我已经找到了他们在带有过滤器选项的角度js中使用它的链接,但是如何在ng-select中完成相同的操作

我尝试在 ng-select 中禁用该选项,如下所示,但如果用户选择另一个选项,我该如何启用以前禁用的值。

change(data) {
const items = this.hardwareIds.slice();
this.hardwareIds.forEach((hardwareId) => {
if (hardwareId.id === data.id) {
hardwareId.disabled =  true;
}
});
this.hardwareIds = [];
this.hardwareIds = [...items];
}

下拉菜单

<ng-select
#sourceSelect
[items]="hardwareIds"
[selectOnTab]="true"
[clearable]="false"
bindValue="id"
bindLabel="hardware_id"
labelForId="source_switch_id"
placeholder="Select source switch id"
formControlName="source_switch_id"
(change)="change($event)"
>
</ng-select>
<ng-select
#destinationSelect
[items]="hardwareIds"
[selectOnTab]="true"
[clearable]="false"
bindValue="id"
bindLabel="hardware_id"
labelForId="dest_switch_id"
placeholder="Select destination switch id"
formControlName="dest_switch_id"
(change)="change($event)"
>
</ng-select>

只需创建两个变量"source"和"dest",并在创建表单后订阅form.valueChanges以过滤值。我使用merge rxjs运算符,你可以有两个订阅,一个用于this.form.get('dest_switch_id'(.valueChanges,另一个用于this.form.get('source_switch_id'(.valueChanges

hardwareIds = [
{ id: 1, hardware_id: "uno" },
{ id: 2, hardware_id: "dos" },
{ id: 3, hardware_id: "tres" },
{ id: 4, hardware_id: "cuatro" },
{ id: 5, hardware_id: "cinco" }
];
form=new FormGroup({
source_switch_id:new FormControl(),
dest_switch_id:new FormControl(),
})
//you create two variables "source" and "dest"
source = this.hardwareIds;
dest = this.hardwareIds;
ngOnInit() {
merge(
this.form.get('dest_switch_id').valueChanges,
this.form.get('source_switch_id').valueChanges
).subscribe(()=>{
this.source = this.hardwareIds.filter(x => x.id != this.form.get('dest_switch_id').value);
this.dest = this.hardwareIds.filter(x => x.id != this.form.get('source_switch_id').value);
})
}
}

在选择中

查看堆叠闪电战

最新更新