2017-03-03 182 views
3

我試圖在Angular 2中實現一個自定義指令,用於移動任意的HTML元素。到目前爲止,所有的工作都在進行中,除了我現在不知道如何獲得HTML元素的初始位置時,我點擊它並且想要開始移動。我結合topleft風格我的HTML元素與兩個主機綁定:Angular 2:獲取HTML元素的位置

/** current Y position of the native element. */ 
@HostBinding('style.top.px') public positionTop: number; 

/** current X position of the native element. */ 
@HostBinding('style.left.px') protected positionLeft: number; 

的問題是,他們兩人都是undefined開頭。我只能更新將更新HTML元素的值,但我無法讀取它?這是否應該是這樣?如果是,還有什麼替代方法可以檢索HTML元素的當前位置。

回答

7
<div (click)="move()">xxx</div> 
// get the host element 
constructor(elRef:ElementRef) {} 

move(ref: ElementRef) { 
    console.log(this.elRef.nativeElement.offsetLeft); 
} 

又見https://stackoverflow.com/a/39149560/217408

+0

但偏移不給我的元素的相對位置? – tom1991te

+0

你的問題沒有提到「相對」。 'offsetLeft'就是一個例子。其餘部分與普通JavaScript相同,這就是爲什麼我將鏈接添加到我的答案。 –