如何在 ng-select 中防止值 selected 跨越多个 select

How to prevent the value selected across multiple select in ng-select

我有两个下拉菜单,它们从同一个 array.If 和 select 第一个下拉菜单中的一个选项获取数据,然后该值在第二个下拉菜单中不可用,反之亦然。

我正在使用 ng-select,但我可以看到与我的问题相关的任何内容。我找到了 他们在 angular js 中使用过滤器选项的地方,但是如何在 ng-select

中完成同样的事情

我已尝试禁用 ng-select 中的选项,如下所示,但如果用户 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);
    })
  }
  }

在select

stackblitz