动态创建打开控件时如何在正确位置打开菜单?

How to open met-menu in correct position when the opening control is created dynamically?

我问了一个问题

关于将自定义控件添加到 openlayers 地图,点击时打开 mat-menu。

我得到了很好的答案,并根据我的实际需要修改了答案。

.html:

<div id="mat-menu-opener" #trig="matMenuTrigger" [matMenuTriggerFor]="menu"></div>
<mat-menu #menu="matMenu" yPosition="below" xPosition="before">
  <button mat-menu-item>Item 1</button>
  <button mat-menu-item>Item 2</button>
</mat-menu>
<app-map-openlayers></app-map-openlayers>

.ts:

  @ViewChild('trig') menuTrigger: MatMenuTrigger;
  map: ol.Map;

  private getContextMenuControl(east: number, north: number): CustomControl {
    const element = document.createElement('div');
    element.className = 'ol-control button menu-opener';

    const pix = this.map.getPixelFromCoordinate([east, north]);
    pix[1] += -40;
    element.style.top = `${pix[0]}px`;
    element.style.left = `${pix[1]}px`;

    element.addEventListener('click', _event =>
      this.menuTrigger.toggleMenu(), false);

    return new CustomControl({ element: element });
  }

  // ... this is called when a feature on map is clicked 
  this.contextMenuControl = this.getContextMenuControl(east, north);
  this.map.addControl(this.contextMenuControl);

但是单击自定义开启器控件不会将菜单打开到正确的位置。它打开它到地图的右上角。如何通过动态创建的自定义开启器控件打开菜单?

我忘了我创建的元素不是真正触发的元素。所以我还需要将触发元素移动到正确的位置。所以它看起来像这样:

  private getContextMenuControl(east: number, north: number): CustomControl {
    const element = document.createElement('div');
    element.className = 'ol-control button menu-opener';

    const pix = this.map.getPixelFromCoordinate([east, north]);
    pix[1] += -40;
    element.style.top = `${pix[0]}px`;
    element.style.left = `${pix[1]}px`;

    // get the static element from template by id
    const menu = document.getElementById('mat-menu-opener');
    if (menu !== null) {
      menu.style.display = '';
      menu.style.position = 'absolute';
      menu.style.left = element.style.left;
      menu.style.top = element.style.top;
    }

    element.addEventListener('click', _event =>
      this.menuTrigger.toggleMenu(), false);

    return new CustomControl({ element: element });
  }