You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在ng-select中将选中选项置于下拉列表顶部?

使用ng-select实现选中项置顶的方案

当然可行,ng-select具备足够的自定义能力来实现这个需求,下面分享几种实用的实现思路:

思路一:通过数据排序实现置顶

核心是在渲染下拉选项前,对数据源进行排序,把已选中的项移到数组最前端:

  • 组件中维护原始选项列表和选中项集合(通过ngModel或change事件获取)
  • 派生一个排序后的选项列表,优先放置已选中项,再拼接未选中项
  • 示例代码:
// 组件内代码
originalOptions = [
  { id: 1, label: '选项A' },
  { id: 2, label: '选项B' },
  { id: 3, label: '选项C' }
];
selectedItems: any[] = [];

// 派生排序后的选项
get sortedOptions() {
  // 先放已选中项,再放未选中项
  return [
    ...this.selectedItems,
    ...this.originalOptions.filter(item => !this.selectedItems.some(selected => selected.id === item.id))
  ];
}

// 配置compareWith确保对象类型选项的选中判断正确
compareWith(item1: any, item2: any) {
  return item1.id === item2.id;
}

模板中绑定排序后的列表:

<ng-select 
  [items]="sortedOptions" 
  [(ngModel)]="selectedItems" 
  [multiple]="true"
  [compareWith]="compareWith"
>
  <ng-template ng-option-tmp let-item="item">
    {{ item.label }}
  </ng-template>
</ng-select>

思路二:通过分组区分选中/未选中项

利用ng-select的groupBy功能,把已选中项单独分成一个组并置顶,视觉区分更清晰:

  • 自定义分组函数,判断项是否属于“已选中”组
  • 示例代码:
// 组件内分组函数
groupBy(item: any) {
  return this.selectedItems.some(selected => selected.id === item.id) ? '已选中' : '可选选项';
}

模板中配置分组:

<ng-select 
  [items]="originalOptions" 
  [(ngModel)]="selectedItems" 
  [multiple]="true"
  [groupBy]="groupBy"
  [compareWith]="compareWith"
>
  <ng-template ng-option-tmp let-item="item">
    {{ item.label }}
  </ng-template>
  <ng-template ng-group-tmp let-group="group">
    <strong>{{ group }}</strong>
  </ng-template>
</ng-select>

思路三:完全自定义下拉模板

如果需要更灵活的布局,直接自定义下拉菜单的整体结构,先渲染已选中项再渲染未选中项:

  • 使用ng-dropdown-tmp模板自定义下拉内容
  • 手动处理选中/取消选中的逻辑
  • 示例模板:
<ng-select 
  [(ngModel)]="selectedItems" 
  [multiple]="true"
  [compareWith]="compareWith"
>
  <ng-template ng-dropdown-tmp>
    <!-- 已选中项区域 -->
    <div class="selected-section">
      <strong>已选中</strong>
      <div 
        class="ng-option" 
        *ngFor="let item of selectedItems"
        (click)="toggleItem(item)"
      >
        {{ item.label }}
      </div>
    </div>
    <!-- 未选中项区域 -->
    <div class="available-section">
      <strong>可选选项</strong>
      <div 
        class="ng-option" 
        *ngFor="let item of originalOptions.filter(i => !selectedItems.some(s => s.id === i.id))"
        (click)="toggleItem(item)"
      >
        {{ item.label }}
      </div>
    </div>
  </ng-template>
</ng-select>

组件内实现切换选中状态的方法:

toggleItem(item: any) {
  const existingIndex = this.selectedItems.findIndex(s => s.id === item.id);
  if (existingIndex > -1) {
    this.selectedItems.splice(existingIndex, 1);
  } else {
    this.selectedItems.push(item);
  }
}

注意事项

  • 若选项是对象类型,必须配置compareWith函数,确保选中状态的判断准确,避免出现重复或选中异常
  • 多选模式下,过滤未选中项时要使用唯一标识(比如id)判断,不要直接用includes比较对象

内容的提问来源于stack exchange,提问作者Haris

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 00:53:18