angualr實現滑鼠拖拽排序功能

大括號啊發表於2018-08-28

angualr2以上版本
我使用的是angualr6.x最新版

ng2-dragula

https://github.com/valor-software/ng2-dragula

1.安裝依賴
npm install ng2-dragula
# or
yarn add ng2-dragula

2.新增這一行到你的 polyfills.ts:
(window as any).global = window;

3.引入模組    DragulaModule.forRoot() 如下:
import { DragulaModule } from `ng2-dragula`;
@NgModule({
  imports: [
    ...,
    DragulaModule.forRoot()
  ],
})
export class AppModule { }

4.引入公用css node_modules/dragula/dist/dragula.css
或者直接複製所有css放styles.scss檔案

5.使用指令,給一個自定義名稱,隨意的字串就行,標識一個div的內容可以拖拽,dragula="div1"和 [dragula]="Vampires"意義等同 程式碼如下
<ul dragula="div1">
  <li>Dracula</li>
  <li>Kurz</li>
  <li>Vladislav</li>
  <li>Deacon</li>
</ul>

6.多個div需要拖拽如下
<div dragula="div1">

</div>
<div dragula="div2">

</div>
<div dragula="div3">

</div>
7. 如果需要雙向繫結拖拽的資料 [(dragulaModel)]

 [(dragulaModel)]等同於 [dragulaModel]="vampires" (dragulaModelChange)="vampires = $event" 類似ng自帶的[(ngModel)]

<ul dragula="VAMPIRES" [(dragulaModel)]="vampires">
  <li *ngFor="let vamp of vampires">
    {{ vamp.name }} likes {{ vamp.favouriteColor }}
  </li>
</ul>
等同於
<ul dragula="VAMPIRES" [dragulaModel]="vampires" (dragulaModelChange)="vampires = $event">
  ...
</ul>

8.拖拽過程中的事件訂閱
import { Subscription } from `rxjs`;
import { DragulaService } from `ng2-dragula`;

export class MyComponent {
  // RxJS Subscription is an excellent API for managing many unsubscribe calls.
  // See note below about unsubscribing.
  subs = new Subscription();

  constructor(private dragulaService: DragulaService) {

    // These will get events limited to the VAMPIRES group.

    this.subs.add(this.dragulaService.drag("VAMPIRES")
      .subscribe(({ name, el, source }) => {
        // ...
      })
    );
    this.subs.add(this.dragulaService.drop("VAMPIRES")
      .subscribe(({ name, el, target, source, sibling }) => {
        // ...
      })
    );
    // some events have lots of properties, just pick the ones you need
    this.subs.add(this.dragulaService.dropModel("VAMPIRES")
      // WHOA
      // .subscribe(({ name, el, target, source, sibling, sourceModel, targetModel, item }) => {
      .subscribe(({ sourceModel, targetModel, item }) => {
        // ...
      })
    );

    // You can also get all events, not limited to a particular group
    this.subs.add(this.dragulaService.drop()
      .subscribe(({ name, el, target, source, sibling }) => {
        // ...
      })
    );
  }

  ngOnDestroy() {
    // destroy all the subscriptions at once
    this.subs.unsubscribe();
  }
}

還有一個非常棒的外掛可以看看
https://github.com/xieziyu/angular2-draggable


相關文章