I have a "popup" that displays data retrieved from a database on mousemove and appears at the mouse location. It looks like this:
<div (mousemove)="onMouseMove($event)></div>
onMouseMove(event: MouseEvent) {
this.xCoord = event.x
this.yCoord = event.y
}
<div [style.left.px]="xCoord" [style.top.px]="yCoord" class="popup">
...
</div>
Because the dimensions of the popup are dynamic, depending on its content, I need to retrieve the dimensions in order for the popup to be placed properly (above the target and centered horizontally). Is it possible in Angular 2 to get style properties from an element without, for example, a mouse event? Ideally, the dimensions are assigned to a variable when the popup appears.
Why don't you just use basic Javascript to access the DOM element's width and height properties, like so:
Javascript:
getPopupDimentions() {
let myElement = getElementById("myPopup");
return {
width: myElement.style.width,
height: myElement.style.height
}
}
HTML:
<div [style.left.px]="xCoord" [style.top.px]="yCoord" class="popup" id="myPopup">
...
</div>
Of course, the Javascript I posted above will need to be called once the popup has been initiated.
If you wanted a more Angular like approach, I would recommend using a View Child, like so:
Javascript:
Make sure you import ViewChild import { Component, ViewChild } from '@angular/core'
@ViewChild('mypopup') mypopup;
getPopupDimentions() {
return {
width: this.mypopup.nativeElement.style.width,
height: this.mypopup.nativeElement.style.height
}
}
HTML:
<div [style.left.px]="xCoord" [style.top.px]="yCoord" class="popup" #mypopup>
...
</div>
If you want to find out more about Angular view children, I recommend checking out this question and its answers.