ITPub博客

首页 > IT职业 > IT生活 > Angular封装拖拽指令

Angular封装拖拽指令

IT生活 作者:xzwsun 时间:2021-09-09 10:03:41 0 删除 编辑

一:创建drag.directive.ts

代码如下:

    

import { Directive, ElementRef, Input,OnInit,Renderer,HostListener} from '@angular/core';


@Directive({ selector: '[myDrag]' })


//封装一个拖拽指令

export class HighlightDirective  implements OnInit {

    constructor(private el: ElementRef,private rr:Renderer) {


    }


    //控制是否按下

    //设置为private,放置外部改变内部数据

    private isDown=false;

    private disX ;

    private disY ;

     

    ngOnInit(){

    this.setColor(this.dragColor);

    }


   

   //点击事件

@HostListener('mousedown',['$event']) onMousedown(event) {

console.log(event);

this.isDown=true;

this.disX=event.clientX-this.el.nativeElement.offsetLeft;

this.disY=event.clientY-this.el.nativeElement.offsetTop;

}

//监听document移动事件事件

@HostListener('document:mousemove', ['$event']) onMousemove(event){

//判断该元素是否被点击了。

if(this.isDown){

  console.log("移动中");

  let newdisX=event.clientX;

  let newdisY=event.clientY;

  this.el.nativeElement.style.left=newdisX-this.disX+"px";

  this.el.nativeElement.style.top=newdisY-this.disY+"px";

  }

 

}

//监听document离开事件

@HostListener('document:mouseup',['$event']) onMouseup() {

//只用当元素移动过了,离开函数体才会触发。

if(this.isDown){

console.log("fail");

this.isDown=false;

}

}


private setColor(color){

this.el.nativeElement.style.background=color;

}


// 绑定到@Input属性

//绑定到@Input别名

//在指令内部,该属性叫dragColor,在外部,当我们绑定到它时,它叫myDrag。

    @Input('myDrag') dragColor: string;

}

二:在根模块引入指令

例如:

    

//注册指令--->用法类似于组件

import {HighlightDirective} from '../directive/drag.directive';

//列出程序中的组件

  declarations: [

    AppComponent,

    GeneralDetailComponent,

    HighlightDirective

  ],

三:使用

<div   [myDrag]="color" >


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/2567/viewspace-2815727/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-08-16

  • 博文量
    100
  • 访问量
    924