首页 > 解决方案 > 找不到嵌套在 mat-grid-tile 中的 HTML 元素

问题描述

我尝试在 amat-grid-tile中显示 openlayers 地图mat-grid-list

模板片段:

<mat-grid-list cols="3" rowHeight="100px">[...]
<mat-grid-tile
      colspan="1"
      rowspan="5">
        <div
          id="map"
          class="map">
        </div>
      </div>
    </mat-grid-tile>[...]
</mat-grid-list>

openlayers 地图在打字稿文件中初始化。片段:

import OlTileLayer from 'ol/layer/Tile';
import OlMap from 'ol/Map';
import OlOverlay from 'ol/Overlay';
import * as proj from 'ol/proj';
import OlXYZ from 'ol/source/XYZ';
import OlView from 'ol/View';
import OlFeature from 'ol/Feature';
import OlVectorSource from 'ol/source/Vector';
import OlStyleStyle from 'ol/style/Style';
import OlIconStyle from 'ol/style/Icon';
import OlOsmSource from 'ol/source/OSM';
import OlVectorLayer from 'ol/layer/Vector';
import OlPoint from 'ol/geom/Point';

[...]
  map: OlMap;
  popup: OlOverlay;
  source: OlXYZ;
  layer: OlTileLayer;
  view: OlView;
  olOverlay: OlOverlay;
  olFeature: OlFeature;
  markerSource: OlVectorSource;
  markerStyle: OlStyleStyle;

ngAfterViewInit(): void {
    this.setMarkerSource();
    this.setMarkerStyle();
    this.setMap();
  }

 private setMap() {
    this.map = new OlMap({
      target: 'map',
      layers: [
        new OlTileLayer({
          source: new OlOsmSource()
        }),
        new OlVectorLayer({
          source: this.markerSource,
          style: this.markerStyle
        })
      ],
      view: new OlView({
        center: proj.fromLonLat([7.35077565, 49.92363955]),
        zoom: 7
      })
    });
  }

  private setMarkerSource() {
    this.markerSource = new OlVectorSource();
  }

  private setMarkerStyle() {
    this.markerStyle = new OlStyleStyle({
      image: new OlIconStyle(
        /** @type {olx.style.IconOptions} */ ({
          opacity: 0.75,
          src: 'path-to-icon.png'
        })
      )
    });
  }

问题是,无法将目标属性设置为 id 为“map”的 div 无法找到。我也试过,document.getElementById('map')但它是空的。首先我在 中进行了地图初始化ngOnInit(),然后将其移至ngAfterViewInit(). 另一种方法是像这样编写 div:

<div #mapDiv class="map></div>

并在 ts 文件中调用它:

@ViewChild('mapDiv')
  mapDiv: ElementRef;
[...]
this.map = new OlMap({
      target: this.mapDiv.nativeElement,
[...]

但它说 this.mapDiv 是未定义的。如果我将地图 div 设置在mat-grid-tile/之外mat-grid-list,它就可以正常工作。

我该怎么做才能把地图放在里面mat-grid-tile?非常感谢。

标签: angular-materialopenlayersangular7

解决方案


非常感谢您的评论。事实上,在停止并重新启动应用程序后,上述代码可以正常工作。不知道是什么问题。


推荐阅读