简体   繁体   English

Angular 8 设置 ngSstyle 和读取 offsetwidth 给出旧值

[英]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 .通过ngStyle设置 styles 时。 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.像下面这样进行操作时,组件将正确呈现,但console.log将显示元素实际 position 的错误值 ( -9999px )。

I do not want to hack it with something like setTimeout.我不想用 setTimeout 之类的东西来破解它。 Is there a better way to do this, or is it possibile to listen to the stylechange??有没有更好的方法来做到这一点,还是可以听风格改变?

component.html组件.html

<div class="context-menu" style="position: fixed; top: -9999px; left: -9999px; z-index: 99999" [ngStyle]="contextMenuStyles" #contextMenu></div>

component.ts组件.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.我不知道为什么会发生这种情况,但是在通过 renderer2 设置 styles 时可以修复它。

So instead of [ngStyle] and this.contextMenuStyles =... i simply use:所以代替 [ngStyle] 和 this.contextMenuStyles =... 我只是使用:

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.这可以通过对多个 styles 使用帮助程序 function 以更优雅的方式完成。 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());
  }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM