We are using drag and drop extensively for creating virtual users in OctoPerf.
As I plan to migrate to Angular2, today I wanted to check how to handle drag and drop in the future of AngularJS.
I started from the W3Schools plain HTML / JS example and created the following component:
import { Component } from 'angular2/core';
@Component({
selector: 'dnd',
directives: [],
styles: [`
.container{
border: 1px solid red;
width: 336px;
height: 69px;
}
`],
template: `
<div id="div1" class="container" (drop)="drop($event)" (dragover)="allowDrop($event)">
<img id="drag1" src="http://www.w3schools.com/html/img_w3slogo.gif" draggable="true"
(dragstart)="drag($event)" width="336" height="69">
</div>
<div id="div2" class="container" (drop)="drop($event)" (dragover)="allowDrop($event)"></div>
`
})
export class DnD {
allowDrop(ev) {
ev.preventDefault();
}
drag(ev) {
ev.dataTransfer.setData("text", ev.target.id);
}
drop(ev) {
ev.preventDefault();
var data = ev.dataTransfer.getData("text");
ev.target.appendChild(document.getElementById(data));
}
}
It’s simple as that. The only things that need to be changed are
- The drop methods:
ondrop
becomes(drop)
, - The
event
parameter becomes$event
.
Comments
Thank you
Your comment has been submitted and will be published once it has been approved.
OK
OOPS!
Your post has failed. Please return to the page and try again. Thank You!
OK
You May Also Like
D3.js Tutorial: Drag and Drop
Learn how to handle drag and drop using D3-drag to manipulate SVG graphics. d3.drag() explained via code samples and live examples.
Angular2: hard time unit testing Http requests
Mocking the Angular2 Http service for unit tests using karma/jasmine.
Angular2: filtering ngFor using pipes
How to filter the content of a table using pipes in Angular2.
Angular2: using TypeScript generics
A sample usage for TypeScript generics when using Angular2 Http service.
Angular2: method callback type in TypeScript
How to set the type for a method callback in TypeScript when using Angular2 Http service.