2017-03-03 188 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相同,这就是为什么我将链接添加到我的答案。 –