Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
604 views
in Technique[技术] by (71.8m points)

typescript - Angular 8 setting ngSstyle and reading offsetwidth gives old values

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

}
question from:https://stackoverflow.com/questions/65888527/angular-8-setting-ngsstyle-and-reading-offsetwidth-gives-old-values

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...