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