Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple drag and drop Angular
import {Component, ElementRef, OnInit, Renderer2, ViewChild} from '@angular/core';
@Component({
selector: 'app-transaction-condition',
styleUrls: ['./transaction-condition.component.css']
template: `
<div class="list" id="list" #list>
<div id="0"
class="item drop-zone"
draggable="true"
(dragstart)="drag($event,0)"
(drop)="drop($event,0)"
(dragover)="allowDrop($event)">
<p>0. Adam</p>
<div><p>Atom</p></div>
</div>
<div id="1"
class="item drop-zone"
draggable="true"
(dragstart)="drag($event,1)"
(drop)="drop($event,1)"
(dragover)="allowDrop($event)">
<p>1. Ben</p>
<div><p>Broke</p></div>
</div>
<div id="2"
class="item drop-zone"
draggable="true"
(dragstart)="drag($event,2)"
(drop)="drop($event,2)"
(dragover)="allowDrop($event)">
<p>2. Charles</p>
<div><p>Crack</p></div>
</div>
<div id="3"
class="item drop-zone"
draggable="true"
(dragstart)="drag($event,3)"
(drop)="drop($event,3)"
(dragover)="allowDrop($event)">
<p>3 Charles</p>
<div><p>Crack</p></div>
</div>
<div id="4"
class="item drop-zone"
draggable="true"
(dragstart)="drag($event,4)"
(drop)="drop($event,4)"
(dragover)="allowDrop($event)">
<p>4. Charles</p>
<div><p>Crack</p></div>
</div>
</div>
`
})
export class TransactionConditionComponent implements OnInit {
@ViewChild('list') list: ElementRef;
private _id: string;
constructor(private renderer2: Renderer2) {
}
ngOnInit() {
}
allowDrop(e) {
e.preventDefault();
}
drag(e, idToMove) {
this._id = idToMove;
}
drop(e, id) {
e.preventDefault();
//to allow dragging down
for (let i = 0; i < this.list.nativeElement.childNodes.length; i++) {
if (parseInt(this._id) === parseInt(this.list.nativeElement.childNodes[i].id)) {
if (typeof this.list.nativeElement.childNodes[i + 1] !== 'undefined') {
if (parseInt(id) === parseInt(this.list.nativeElement.childNodes[i + 1].id)) {
let aux = this._id;
this._id = id;
id = aux;
}
}
else {
if (parseInt(id) === parseInt(this.list.nativeElement.childNodes[i].id)) {
let aux = this._id;
this._id = id;
id = aux;
}
}
}
}
this.renderer2.insertBefore(this.list.nativeElement, document.getElementById(this._id), document.getElementById(id));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment