1. Instruction code
import { Directive, ElementRef, OnInit, HostListener } from '@angular/core'; @Directive({ selector: '[appDrag]' }) export class DragDirective implements OnInit { constructor(public el: ElementRef) { } public isDown = false; public disX; // Record the location of the mouse click event X public disY; // Record the location of the mouse click event Y private totalOffsetX = 0; // Record the total offset X-axis private totalOffsetY = 0; // Record the total offset Y-axis // Click event @HostListener('mousedown', ['$event']) onMousedown(event) { = true; = ; = ; } // Listen to document mobile event events @HostListener('document:mousemove', ['$event']) onMousemove(event) { // Determine whether the element has been clicked. if () { = + - + 'px'; = + - + 'px'; } } // Listen to document leaving event @HostListener('document:mouseup', ['$event']) onMouseup(event) { // It will only trigger when the element has moved past and leaving the function body. if () { ('fail'); += - ; += - ; = false; } } ngOnInit() { = 'relative'; } }
2. Use
First register the command in the Module,declarations
Add instructions to the array.
Then add instructions on the component you want to drag.appDrag
, you can realize the drag and drop function.
The above is the detailed explanation of the drag function drag example of Angular6. For more information about Angular6 drag function drag, please follow my other related articles!