Angular 4: 访问一个 Openlayers 'overlay' 元素

Angular 4: access an Openlayers 'overlay' element

如何在 Angular 中使用 Openlayer 'overlay'?我认为最好的方法是通过 @Viewchild 构造。所以,不是通过 document.getElementById('overlay').

在 HTML 文件中我有类似的东西。

<div #overlayElement id="overlay" style="background-color: yellow; width: 20px; height: 20px; border-radius: 10px;">
<div #mapElement id="map" class="map"> </div>

非Angular解决方案是通过“元素:document.getElementById('overlay')”将覆盖逻辑附加到Html 'overlay'元素.这样可行。

更新:感谢@zerO,逻辑从构造函数移到了ngOnInit()。

在我的 Angular 组件中,我希望附加带有视图标签“#overlayElement”的叠加层 Html 元素。在我的组件代码中,我希望通过 @Viewchild 访问它。我收到一个奇怪的 [Object object] 错误。

declare var ol: any;

@Component({
  selector: 'app-tab4-controls',
  templateUrl: './tab4-controls.component.html',
  styleUrls: ['./tab4-controls.component.css']
})
export class Tab4ControlsComponent implements AfterViewInit, OnInit {

@ViewChild('mapElement') mapElement: ElementRef;
@ViewChild('overlayElement') overlayElement: ElementRef;
public map: any;

constructor() { }

ngOnInit(): void {

  const layer = new ol.layer.Tile({
    source: new ol.source.OSM()
  });
  const interaction = new ol.interaction.DragRotateAndZoom();
  const control = new ol.control.FullScreen();
  const center = ol.proj.transform([-1.812, 52.443], 'EPSG:4326', 'EPSG:3857');
  const overlay = new ol.Overlay({
    position: center,
    // element: document.getElementById('overlay') <== this works
    element : this.overlayElement.nativeElement.id
  });
  const view = new ol.View({
    center: center,
    zoom: 6
  });
  this.map = new ol.Map({
    layers: [layer],
    interactions: [interaction],
    controls: [control],
    overlays: [overlay],
    view: view
  });
}

ngAfterViewInit() {
    this.map.setTarget(this.mapElement.nativeElement.id);
}

我认为 constructor 访问它可能为时过早。你能试着把它放在 ngOnInit()ngAfterViewInit() 吗?