Angular 8 setting ngSstyle and reading offsetwidth gives old values

129 Views Asked by At

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());
  }

}
1

There are 1 best solutions below

0
On BEST ANSWER

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.renderer.setStyle(this.contextMenu.nativeElement, 'top', top);
this.renderer.setStyle(this.contextMenu.nativeElement, 'left', left);

This can be done in a more elegant way using a helper function for multiple styles. Like this for example:

Class XXX {

  constructor(private renderer: Renderer2) {}

  onContextmenu($event: MouseEvent) {
    $event.preventDefault();

    const setStyles = <DomElement, StyleObj>(domEl: DomElement, styles: StyleObj) => {
      Object.keys(styles).forEach((styleName) => {
        this.renderer.setStyle(domEl, styleName, styles[styleName]);
      });
    };

    setStyles(this.contextMenu.nativeElement, {
      top: `${$event.y}px`,
      left: `${$event.x}px`,
    });

    console.log(this.contextMenu.nativeElement.getBoundingClientRect());
  }

}