Angular2封装拖拽指令
一:創(chuàng)建drag.directive.ts
代碼如下:
????
/*
1.Directive提供@Directive裝飾器功能。
2.ElementRef注入到指令構(gòu)造函數(shù)中。這樣代碼就可以訪問 DOM 元素了。
3.Input將數(shù)據(jù)從綁定表達(dá)式傳達(dá)到指令中。
*/
import { Directive, ElementRef, Input,OnInit,Renderer,HostListener} from '@angular/core';
/*
@Directive裝飾器函數(shù)以配置對象參數(shù)的形式,包含了指令的元數(shù)據(jù)。
@Directive裝飾器需要一個 CSS 選擇器,以便從模板中識別出關(guān)聯(lián)到這個指令的 HTML。
*/
@Directive({ selector: '[myDrag]' })
//封裝一個拖拽指令
export class HighlightDirective ?implements OnInit {
/*
ElementRef是一個服務(wù),它賦予我們通過它的nativeElement屬性直接訪問 "DOM 元素"的能力
。 Renderer服務(wù)允許通過代碼設(shè)置"元素的樣式"。
*/
? ? constructor(private el: ElementRef,private rr:Renderer) {
? ? }
? ? //控制是否按下
? ? //設(shè)置為private,放置外部改變內(nèi)部數(shù)據(jù)
? ? private isDown=false;
? ? private disX ;
? ? private disY ;
? ? ?
? ? ngOnInit(){
? ? this.setColor(this.dragColor);
? ? }
? ? /*
@HostListener裝飾器引用屬性型指令的宿主元素
當(dāng)然,你可以通過標(biāo)準(zhǔn)的JavaScript方式手動給宿主 DOM 元素附加一個事件監(jiān)聽器。 但這種方法至少有三個問題:
1.必須正確的書寫事件監(jiān)聽器。
2.當(dāng)指令被銷毀的時候,必須拆卸事件監(jiān)聽器,否則會導(dǎo)致內(nèi)存泄露。
3.必須直接和 DOM API 打交道,應(yīng)該避免"這樣做"。
@HostListener的this的指向很重要
? ? */
? ?//點(diǎn)擊事件
@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;
}
//監(jiān)聽document移動事件事件
@HostListener('document:mousemove', ['$event']) onMousemove(event){
//判斷該元素是否被點(diǎn)擊了。
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";
? }
?
}
//監(jiān)聽document離開事件
@HostListener('document:mouseup',['$event']) onMouseup() {
//只用當(dāng)元素移動過了,離開函數(shù)體才會觸發(fā)。
if(this.isDown){
console.log("fail");
this.isDown=false;
}
}
private setColor(color){
this.el.nativeElement.style.background=color;
}
/*
使用數(shù)據(jù)綁定向指令傳遞值
注意看@Input裝飾器。它往類上添加了一些元數(shù)據(jù),從而讓該指令的highlightColor能用于綁定。
它之所以稱為輸入屬性,是因?yàn)閿?shù)據(jù)流是從綁定表達(dá)式流向指令內(nèi)部的。 如果沒有這個元數(shù)據(jù),Angular就會拒絕綁定,
*/
// 綁定到@Input屬性
//綁定到@Input別名
//在指令內(nèi)部,該屬性叫dragColor,在外部,當(dāng)我們綁定到它時,它叫myDrag。
? ? @Input('myDrag') dragColor: string;
}
二:在根模塊引入指令
例如:
????
//注冊指令--->用法類似于組件
import {HighlightDirective} from '../directive/drag.directive';
//列出程序中的組件
? declarations: [
? ? AppComponent,
? ? GeneralDetailComponent,
? ? HighlightDirective
? ],
三:使用
<div ? [myDrag]="color" style="height:200px;width:200px;position: absolute;">
轉(zhuǎn)載于:https://blog.51cto.com/12907581/1966860
總結(jié)
以上是生活随笔為你收集整理的Angular2封装拖拽指令的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 安装最新版git,git升级
- 下一篇: 只用一招,让你Maven依赖下载速度快如