Angular2封装拖拽指令
一:創建drag.directive.ts
代碼如下:
????
/*
1.Directive提供@Directive裝飾器功能。
2.ElementRef注入到指令構造函數中。這樣代碼就可以訪問 DOM 元素了。
3.Input將數據從綁定表達式傳達到指令中。
*/
import { Directive, ElementRef, Input,OnInit,Renderer,HostListener} from '@angular/core';
/*
@Directive裝飾器函數以配置對象參數的形式,包含了指令的元數據。
@Directive裝飾器需要一個 CSS 選擇器,以便從模板中識別出關聯到這個指令的 HTML。
*/
@Directive({ selector: '[myDrag]' })
//封裝一個拖拽指令
export class HighlightDirective ?implements OnInit {
/*
ElementRef是一個服務,它賦予我們通過它的nativeElement屬性直接訪問 "DOM 元素"的能力
。 Renderer服務允許通過代碼設置"元素的樣式"。
*/
? ? constructor(private el: ElementRef,private rr:Renderer) {
? ? }
? ? //控制是否按下
? ? //設置為private,放置外部改變內部數據
? ? private isDown=false;
? ? private disX ;
? ? private disY ;
? ? ?
? ? ngOnInit(){
? ? this.setColor(this.dragColor);
? ? }
? ? /*
@HostListener裝飾器引用屬性型指令的宿主元素
當然,你可以通過標準的JavaScript方式手動給宿主 DOM 元素附加一個事件監聽器。 但這種方法至少有三個問題:
1.必須正確的書寫事件監聽器。
2.當指令被銷毀的時候,必須拆卸事件監聽器,否則會導致內存泄露。
3.必須直接和 DOM API 打交道,應該避免"這樣做"。
@HostListener的this的指向很重要
? ? */
? ?//點擊事件
@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裝飾器。它往類上添加了一些元數據,從而讓該指令的highlightColor能用于綁定。
它之所以稱為輸入屬性,是因為數據流是從綁定表達式流向指令內部的。 如果沒有這個元數據,Angular就會拒絕綁定,
*/
// 綁定到@Input屬性
//綁定到@Input別名
//在指令內部,該屬性叫dragColor,在外部,當我們綁定到它時,它叫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;">
轉載于:https://blog.51cto.com/12907581/1966860
總結
以上是生活随笔為你收集整理的Angular2封装拖拽指令的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 安装最新版git,git升级
- 下一篇: 只用一招,让你Maven依赖下载速度快如