1+ import { Directive , ElementRef , Renderer , OnDestroy , OnInit } from '@angular/core' ;
2+
3+
4+ @Directive ( {
5+ selector : '[draggable]' ,
6+ host : {
7+ '(dragstart)' : 'onDragStart($event)' ,
8+ '(dragend)' : 'onDragEnd($event)' ,
9+ '(drag)' : 'onDrag($event)'
10+ }
11+ } )
12+ export class Draggable implements OnDestroy , OnInit {
13+ private Δx : number = 0 ;
14+ private Δy : number = 0 ;
15+ private mustBePosition : Array < string > = [ 'absolute' , 'fixed' , 'relative' ] ;
16+ constructor (
17+ private el : ElementRef , private renderer : Renderer
18+ ) {
19+ try {
20+ if ( this . mustBePosition . indexOf ( this . el . nativeElement . style . position ) === - 1 ) {
21+ console . warn ( this . el . nativeElement , 'Must be having position attribute set to ' + this . mustBePosition . join ( '|' ) ) ;
22+ }
23+ } catch ( ex ) {
24+ console . error ( ex ) ;
25+ }
26+ }
27+ public ngOnInit ( ) : void {
28+ this . renderer . setElementAttribute ( this . el . nativeElement , 'draggable' , 'true' ) ;
29+ }
30+ onDragStart ( event : MouseEvent ) {
31+ this . Δx = event . x - this . el . nativeElement . offsetLeft ;
32+ this . Δy = event . y - this . el . nativeElement . offsetTop ;
33+ }
34+ onDrag ( event : MouseEvent ) {
35+ this . doTranslation ( event . x , event . y ) ;
36+ }
37+ onDragEnd ( event : MouseEvent ) {
38+ this . Δx = 0 ;
39+ this . Δy = 0 ;
40+ }
41+ doTranslation ( x : number , y : number ) {
42+ if ( ! x || ! y ) return ;
43+ this . renderer . setElementStyle ( this . el . nativeElement , 'top' , ( y - this . Δy ) + 'px' ) ;
44+ this . renderer . setElementStyle ( this . el . nativeElement , 'left' , ( x - this . Δx ) + 'px' ) ;
45+ }
46+ public ngOnDestroy ( ) : void {
47+ this . renderer . setElementAttribute ( this . el . nativeElement , 'draggable' , 'false' ) ;
48+ }
49+
50+ }
51+
52+ import { NgModule } from '@angular/core' ;
53+ import { CommonModule } from '@angular/common' ;
54+
55+
56+ const DRAGGABLE_DIRECTIVES : any [ ] = [ Draggable ] ;
57+
58+ @NgModule ( {
59+ imports : [ CommonModule ] ,
60+ exports : DRAGGABLE_DIRECTIVES ,
61+ declarations : DRAGGABLE_DIRECTIVES
62+ } )
63+ export class DraggableModule { }
0 commit comments