检查 p-multiSelect PrimeNG 的列选项的元素在数组末尾添加相关列

Check element of columnoptions of p-multiSelect PrimeNG add the concerned column in the end of array

是否有任何解决方案可以使 PrimeNG 的 check/uncheck 元素 p-multiselect 保持绑定数组的列顺序?

(实际上,当我们取消选中一个元素时,它会从数组的列中消失,但当我们重新选中时,该列会添加到数组的末尾,而不是初始索引中)

您可以在 选项 中添加 position 属性。然后,您所要做的就是添加 onChange 事件并使用 position 属性.

重新排序 selectedOptions

HTML

<p-multiSelect [options]="cars" [(ngModel)]="selectedCars1" [panelStyle]="{minWidth:'12em'}" (onChange)="reorderValues($event)"></p-multiSelect>

TS

    // add position property
    this.cars.forEach(function (car, i) {
      car.value = { position: i, value: car.value };
    });

  reorderValues(event) {
    this.selectedCars1.sort(function (a: any, b: any) { return (a.position > b.position) ? 1 : ((b.position > a.position) ? -1 : 0); });
  }

编辑

如果你想让这个多选字段成为必填,请在其上添加验证。

  validateForm() {
    this.showMultiselectRequiredMessage = (this.selectedCars1.length === 0) ? true : false;
  }

StackBlitz