ngx-bootstrap Sortable 复杂数据模型实战:对象列表跨容器拖拽与模型同步

原创2026-10-12 14:48:561,628 阅读
文章标签:UI组件前端

ngx-bootstrap Sortable 复杂数据模型实战:对象列表跨容器拖拽与模型同步

本篇指南围绕 ngx-bootstrap Sortable 组件的 Complex data model(复杂数据模型) 示例展开,该示例位于 docs/spec/sortable/sortable.examples.complex-data-model.use-case.md,对应官方文档页中 Sortable 模块的第二个示例子菜单。文中将完整还原该示例的组件代码与模板,并结合 src/sortable 下的组件源码、拖拽服务与单元测试,深入讲解对象型列表(每个元素包含 id、name 等字段)如何接入 bs-sortable、如何利用 fieldName 指定显示字段、如何在两个列表之间拖拽移动并实时同步模型,以及列表清空时 "Drag here" 占位提示的实现原理。读完本文,你可以直接把这套模式套用到任何“双栏可拖拽分配”的实战表单场景。

一、示例定位:这个 use case 在讲什么

按 use case 的原始定义(Primary Actor: User,Scope: Ngx-bootstrap DEMO / BS version 3&4,Goal: Show user sortable functionality with complex data model),该示例要验证的主成功场景为:

  1. 用户打开 Sortable 示例页面;
  2. 点击 Complex data model 子菜单;
  3. 默认看到 2 个 bs-sortable 组件,每个组件各含 3 个条目;
  4. 每个组件下方都有代码预览块,展示各自的模型(每个对象都包含 id 和 name 字段);
  5. 当用户把条目从第一个列表拖到第二个列表时,该条目出现在第二个列表中,且两边模型同步变化;
  6. 当第一个列表所有条目都被移走后,显示文本 "Drag here",且该模型为空;
  7. 当把第二个列表所有条目都移回第一个列表时,第二个列表同样显示 "Drag here",其模型为空,而第一个列表恢复包含全部 6 个条目。

变体场景(Variations)仅有一条:2* 用户通过滚动方式定位到该子菜单。也就是说,功能验证点与"点击进入"等价,只需保证该示例在页面上可见、可操作即可。

二、完整示例代码:从 use case 到可运行实现

use case 只描述了行为,仓库中真实承载该示例的是 libs/doc-pages/sortable(演示文档库)下的 Complex data model 演示组件,并被注册进 Sortable 文档页的路由与分区列表(见 sortable-section.list.ts,标题 Complex data model,anchor complexDatamodel)。

2.1 组件类(模型定义)

见 complex-datamodel.component.ts:

import { Component } from '@angular/core';

interface IItemObject {
  id: number;
  name: string;
}

@Component({
  // eslint-disable-next-line @angular-eslint/component-selector
  selector: 'complex-datamodel-demo',
  templateUrl: './complex-datamodel.component.html',
  standalone: false
})
export class ComplexDatamodelDemoComponent {
  itemObjectsLeft: IItemObject[] = [
    { id: 1, name: 'Windstorm' },
    { id: 2, name: 'Bombasto' },
    { id: 3, name: 'Magneta' }
  ];

  itemObjectsRight: IItemObject[] = [
    { id: 4, name: 'Tornado' },
    { id: 5, name: 'Mr. O' },
    { id: 6, name: 'Tomato' }
  ];
}

这与 use case 第 3、4 步完全对应:左右两个列表各 3 个条目,每个对象含 id 与 name。与基础示例(basic.component.ts)中直接使用字符串数组不同,这里演示的是对象数组的接入方式。

2.2 模板(双向绑定 + fieldName)

见 complex-datamodel.component.html:

<div class="row">
  <div class="col-xs-6 col-6 col-md-5 col-lg-3">
    <bs-sortable
      [(ngModel)]="itemObjectsLeft"
      fieldName="name"
      itemClass="sortable-item"
      itemActiveClass="sortable-item-active"
      placeholderItem="Drag here"
      placeholderClass="placeholderStyle text-center"
      wrapperClass="sortable-wrapper"
    ></bs-sortable>
  </div>
  <div class="col-xs-6 col-6 col-md-5 col-lg-3">
    <bs-sortable
      [(ngModel)]="itemObjectsRight"
      fieldName="name"
      itemClass="sortable-item"
      itemActiveClass="sortable-item-active"
      placeholderItem="Drag here"
      placeholderClass="placeholderStyle text-center"
      wrapperClass="sortable-wrapper"
    ></bs-sortable>
  </div>
</div>

<div class='row'>
  <div class="col-xs-6 col-6 col-md-5 col-lg-3">
    <pre class="code-preview">model: {{ itemObjectsLeft | json }}</pre>
  </div>

  <div class="col-xs-6 col-6 col-md-5 col-lg-3">
    <pre class="code-preview">model: {{ itemObjectsRight | json }}</pre>
  </div>
</div>

要点解读:

  • [(ngModel)]="itemObjectsLeft" / [(ngModel)]="itemObjectsRight":bs-sortable 实现了 ControlValueAccessor,因此可以直接使用 Angular 表单双向绑定,拖拽后模型自动回写;
  • fieldName="name":复杂数据模型示例的关键配置,它告诉组件从对象中读取哪个字段作为条目显示文本(这里是 name);
  • placeholderItem="Drag here":对应 use case 第 6、7 步——列表被清空后显示的占位文案;
  • 两个 <pre class="code-preview"> 用 | json 实时打印模型,正是 use case 第 4 步"code-preview block with appropriate models"的实现。

三、源码级原理:fieldName 与对象模型的内部映射

3.1 writeValue 如何消化对象数组

bs-sortable 组件的核心实现位于 src/sortable/sortable.component.ts。当外部通过 ngModel 写入对象数组时,组件走 writeValue 分支:

writeValue(value: any[]): void {
  if (value) {
    const fieldNameValue = this.fieldName();
    this.items = value.map((x: any, i: number) => ({
      id: i,
      initData: x,
      value: fieldNameValue ? x[fieldNameValue] : x
    }));
  } else {
    this.items = [];
  }
  this.updatePlaceholderState();
}

这里发生了关键转换:数组中的每个原始对象被包装为内部结构 SortableItem(见同文件底部接口声明):

export declare interface SortableItem {
  id: number;
  value: string;
  initData: any;
}
  • id 为数组下标(用于定位);
  • initData 保留原始对象引用,拖拽结束时原样回写模型;
  • value 是渲染显示的字符串:当设置了 fieldName 时取 x[fieldNameValue](即本例中的 x.name),未设置时则直接取元素本身(字符串数组场景)。

这正是"复杂数据模型"与"基础字符串模型"在内部唯一的区别点,也是 fieldName 的底层语义所在。默认渲染模板 {{item.value}}(见 sortable.component.ts 中 defItemTemplate)输出的正是这个 value 字段。

3.2 items setter 与模型回写

内部数组每次变化都会经过 items 的 setter(sortable.component.ts):

set items(value: SortableItem[]) {
  this._items = value;
  const out = this.items.map((x: SortableItem) => x.initData);
  this.onChanged(out);        // 回写 ngModel
  this.onChange.emit(out);    // 触发 onChange 输出事件
}

即拖拽引起排序/插入/删除时,组件把内部包装数组还原为原始对象数组(initData 序列),同时通过 onChanged(注册自 registerOnChange)回写 [(ngModel)],并向外发出 onChange 事件——这就是 use case 第 5 步"model changed appropriate"的机制。组件还声明了独立的输出属性 onChange = output<unknown[]>(),官方注释明确"fired on array change (reordering, insert, remove),同 ngModelChange,返回新的 items 集合作为载荷"。

3.3 占位提示 updatePlaceholderState

列表清空后显示 "Drag here" 由 updatePlaceholderState 控制(sortable.component.ts):

updatePlaceholderState(): void {
  this.showPlaceholder = !this._items.length;
}

模板中对应(sortable.component.ts):当 showPlaceholder 为真时渲染一个占位 div,显示 placeholderItem() 文本(即 "Drag here")。writeValue、onItemDragover、onDrop 三处都会调用它,保证"移出最后一个条目后立即出现占位"、"放入第一个条目后占位立即消失"。

四、跨列表拖拽的数据流:DraggableItemService 与区域索引

use case 的核心行为是"从第一个列表拖到第二个列表"。跨列表协作依赖单例服务 src/sortable/draggable-item.service.ts,其携带的数据结构 draggable-item.ts 定义如下:

export interface DraggableItem {
  event: DragEvent;
  item: any;
  i: number;
  initialIndex: number;
  lastZoneIndex: number;
  overZoneIndex: number;
}

关键概念是 zone(区域)索引:每个 SortableComponent 实例在构造时通过 SortableComponent.globalZoneIndex++ 获得全局唯一的 currentZoneIndex(见 sortable.component.ts),因此左右两个列表天然属于不同 zone。

拖拽完整链路:

  1. dragstart:onItemDragstart 调用 transfer.dragStart({ event, item, i, initialIndex, lastZoneIndex, overZoneIndex }),把被拖条目存入服务(sortable.component.ts);同时 initDragstartEvent 以 'Text' 类型写入 dataTransfer(源码注释说明这是为兼容 Mozilla 与 IE 的必要处理);
  2. dragover(目标列表):onItemDragover 先 preventDefault,再调用 transfer.captureItem(当前zone, 长度);captureItem 检测到 overZoneIndex 变化(跨列表)时,先记录 lastZoneIndex,再通过 onCapture Subject 通知原列表,并让自身订阅 onCaptureItem() 的组件执行 onDrop(draggable-item.service.ts);
  3. onDrop(原列表):当 overZoneIndex !== 本zone 且 lastZoneIndex === 本zone 时,从原列表 filter 掉该条目并再次 updatePlaceholderState(sortable.component.ts);
  4. onItemDragover(目标列表):按拖拽方向执行 slice 重组——dragItem.i > i 时前插,否则后插,重组结果赋给 items setter,随即触发模型回写(sortable.component.ts)。

空列表的插入也有专门分支:if (!this.items.length) newArray = [dragItem.item],即直接放入第一个条目。

五、SortableComponent 全部输入输出参数

结合 sortable.component.ts 的声明,复杂数据模型示例实际用到的配置只是其中一部分,完整可配置项如下:

参数 类型 示例中的值 说明
fieldName string name 输入数组为对象时,指定作为条目显示文本的字段名;不设置则直接渲染元素本身
wrapperClass string sortable-wrapper 列表容器的 CSS 类
wrapperStyle Record<string, string> — 列表容器的内联样式对象
itemClass string sortable-item 每个条目的 CSS 类
itemStyle Record<string, string> — 条目默认内联样式
itemActiveClass string sortable-item-active 正在拖拽/激活条目的 CSS 类(叠加在 itemClass 上)
itemActiveStyle Record<string, string> — 激活条目的内联样式(与 itemStyle 合并)
placeholderClass string placeholderStyle text-center 空列表占位块的 CSS 类
placeholderStyle Record<string, string> — 占位块内联样式
placeholderItem string Drag here 空列表显示的占位文案
itemTemplate TemplateRef — 自定义条目模板,模板上下文变量为 item 和 index(见 Custom item template 示例)
onChange(输出) unknown[] — 数组变化(排序、插入、移除)时触发,载荷为新的 items 集合,等价于 ngModelChange

另外 bs-sortable 声明为 exportAs: 'bs-sortable'、standalone: true,模板条目带有 draggable="true"、aria-dropeffect="move" 与动态的 aria-grabbed,说明拖拽行为完全基于 HTML5 Drag and Drop API 实现,不依赖第三方拖拽库。

六、测试佐证:对象模型路径已被单元测试覆盖

源码单元测试 src/sortable/testing/sortable.component.spec.ts 直接为复杂对象模型场景提供了验证:

const HEROES_OBJ: { id: number; name: string }[] = [
  { id: 1, name: 'Windstorm' },
  { id: 2, name: 'Bombasto' },
  { id: 3, name: 'Magneta' }
];
// 模板中第二个 sortable:
// <bs-sortable id="sort2" [(ngModel)]="heroesObj" [fieldName]="'name'" [placeholderItem]="'empty'"></bs-sortable>

it('should render list of complex models', () => {
  const renderedItems = getItemsByContainerId('sort2');
  expect(renderedItems).toEqual(HEROES_OBJ.map((h: any) => h.name));
});

该用例证明:传入对象数组并设置 fieldName='name' 后,组件渲染出的条目文本恰为对象的 name 字段序列。测试还覆盖了同区间拖拽的多种位移(首尾移动、交换、空列表插入)、跨容器移除/不移除、onChanged 回写载荷以及激活样式合并逻辑(getItemStyle(true) 为 itemStyle 与 itemActiveStyle 的合并结果),可作为本文前述机制的行为佐证。相关服务单测见 draggable-item.service.spec.ts。

七、安装与接入方式

Sortable 模块的官方接入方式记录在 libs/doc-pages/sortable/src/lib/docs/usage.md,文档站安装页还提供了 CLI 命令 ng add ngx-bootstrap --component sortable(见 sortable-section.list.ts)。

模块方式:

import { SortableModule } from 'ngx-bootstrap/sortable';

@NgModule({
  imports: [SortableModule, ...]
})
export class AppModule() {}

Standalone 方式(SortableModule 内部只是转发 standalone 的 SortableComponent,见 sortable.module.ts):

import { SortableModule } from 'ngx-bootstrap/sortable';

@Component({
  standalone: true,
  imports: [SortableModule, ...]
})
export class AppComponent() {}

公开 API 汇总于 public_api.ts:SortableModule、SortableComponent、SortableItem、DraggableItemService、DraggableItem。注意 bs-sortable 依赖 [(ngModel)],因此使用场景所在模块还需引入 FormsModule。

八、小结:把复杂数据模型模式迁移到自己的业务

从 use case 定义到仓库实现,Complex data model 示例的可复用结论可以归纳为三条:

  1. 对象数组接入零成本:只要给 bs-sortable 加上 fieldName="xxx",内部 writeValue 会完成对象→SortableItem{id, value, initData} 的包装,拖拽结束后又通过 initData 原样回写对象数组,id、name 之外的字段全程无损;
  2. 双列表互拖是默认能力:每个组件实例有独立 zone 索引,配合单例 DraggableItemService,跨列表拖拽(原列表移除 + 目标列表插入)与同列表排序共用一套数据流,无需额外配置;
  3. 空态体验内置:placeholderItem="Drag here" 配合 updatePlaceholderState,当列表被搬空时自动展示占位文案,模型与界面保持同步。

后续若需要自定义每一条目的展示样式(例如带索引号),可参考同模块下的 Custom item template 示例 及其实现 custom-item-template.ts,通过 itemTemplate 输入传入 ng-template(上下文变量 item、index)即可。

登录后查看全文
ngx-bootstrap