tzw*_*ckl 5 html5 angular2-hostbinding angular
我正在尝试在Angular 2中实现一个自定义指令,用于移动任意HTML元素.到目前为止一切正常,但我现在不知道如何在点击它并想要开始移动时获取HTML元素的初始位置.我结合top和left风格与这两个主机绑定我的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;
Run Code Online (Sandbox Code Playgroud)
问题在于它们都undefined处于起步阶段.我只能更新也会更新HTML元素的值,但我无法读取它?那是假设那样吗?如果是,我有什么替代方法来检索HTML元素的当前位置.
Gün*_*uer 20
<div (click)="move()">xxx</div>
Run Code Online (Sandbox Code Playgroud)
// get the host element
constructor(elRef:ElementRef) {}
move(ref: ElementRef) {
console.log(this.elRef.nativeElement.offsetLeft);
}
Run Code Online (Sandbox Code Playgroud)
小智 10
在 html 中:
<div (click)="getPosition($event)">xxx</div>
Run Code Online (Sandbox Code Playgroud)
在打字稿中:
getPosition(event){
let offsetLeft = 0;
let offsetTop = 0;
let el = event.srcElement;
while(el){
offsetLeft += el.offsetLeft;
offsetTop += el.offsetTop;
el = el.parentElement;
}
return { offsetTop:offsetTop , offsetLeft:offsetLeft }
}
Run Code Online (Sandbox Code Playgroud)
小智 6
在typeScript中,您可以获得以下位置:
@ViewChild('ElementRefName') element: ElementRef;
const {x, y} = this.element.nativeElement.getBoundingClientRect();
Run Code Online (Sandbox Code Playgroud)