I am having trouble getting the correct values for a small custom context menu. When setting the styles via ngStyle
. When doing it like below the componen will be rendered correctly, but the console.log
will show the wrong values (-9999px
) for the actual position of the element.
I do not want to hack it with something like setTimeout. Is there a better way to do this, or is it possibile to listen to the stylechange!?
component.html
<div class="context-menu" style="position: fixed; top: -9999px; left: -9999px; z-index: 99999" [ngStyle]="contextMenuStyles" #contextMenu></div>
component.ts
Class XXX {
onContextmenu($event: MouseEvent) {
$event.preventDefault();
const top = `${$event.y}px`;
const left = `${$event.x}px`;
this.contextMenuStyles = {top, left};
console.log(this.contextMenu.nativeElement.getBoundingClientRect());
}
}
I don't know WHY this happens, but it can be fixed when setting the styles via renderer2.
So instead of [ngStyle] and this.contextMenuStyles = ... i simply use:
This can be done in a more elegant way using a helper function for multiple styles. Like this for example: