我正在尝试在 Angular 2 中实现一个自定义指令,用于移动任意 HTML 元素。到目前为止,一切正常,除了我现在不知道如何在单击它并想开始移动时获取 HTML 元素的初始位置。我用这两个主机绑定(bind)绑定(bind)到我的 HTML 元素的 top
和 left
样式:
/** 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 元素的当前位置。
最佳答案
<div (click)="move()">xxx</div>
// get the host element
constructor(elRef:ElementRef) {}
move(ref: ElementRef) {
console.log(this.elRef.nativeElement.offsetLeft);
}
关于html - Angular 2 : Get position of HTML element,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42576008/