OpenLayers 5 |角度7 |角材料|贴图在角材料垫步进器内部不起作用

时间:2019-02-16 12:16:34

标签: angular typescript angular-material openlayers angular7

我已经在组件ts文件中导入了OpenLayers映射,然后我创建了一个id = map的div块,必须在其中显示OpenLayers映射,但事实并非如此。当我将div块(#map)移到mat-stepper块之外时,它就起作用了。

Component.ts:

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

import OlMap from 'ol/Map';
import OlXYZ from 'ol/source/XYZ';
import OlTileLayer from 'ol/layer/Tile';
import OlView from 'ol/View';
import { fromLonLat } from 'ol/proj';

@Component({
  selector: 'app-sell',
  templateUrl: './sell.component.html',
  styleUrls: ['./sell.component.scss'],
})
export class SellComponent implements OnInit {
  ...

  map: OlMap;
  source: OlXYZ;
  layer: OlTileLayer;
  view: OlView;

  ...

  ngOnInit() {
    this.source = new OlXYZ({
      url: 'http://tile.osm.org/{z}/{x}/{y}.png',
    });

    this.layer = new OlTileLayer({
      source: this.source,
    });

    this.view = new OlView({
      center: fromLonLat([6.661594, 50.433237]),
      zoom: 3,
    });

    this.map = new OlMap({
      target: 'map',
      layers: [this.layer],
      view: this.view,
    });
  }

Component.html:

<mat-horizontal-stepper
  linear
  labelPosition="bottom"
  #stepper
  class="sell-form-container"
>
  <mat-step ...>
    <form ...>
      ...
      <div id="map"></div>  //<- here it does not work, map does not display
      ...
    </form>
  </mat-step>
  ...
</mat-horizontal-stepper>
<div id="map"></div> //<- here it works, map displays

Component.css:

#map {
  width: 100%;
  height: 500px;
}

我的代码有什么问题?

1 个答案:

答案 0 :(得分:0)

我相信您的问题与您试图将OLMap附加到mat-stepper或mat-step的已包含内容中有关。

在组件生命周期中,子组件未在父组件的OnInit步骤准备就绪。因为您将div放在了mat组件内部,所以它被包含在该组件的生命周期中。

您应该能够解决此问题的一种方法是使用ngAfterViewInit生命周期方法。将您的代码包含在该方法中应该可以解决此问题。

ngAfterViewInit() {
  this.map = new OlMap({
    target: 'map',
    layers: [this.layer],
    view: this.view,
  });
}

出于潜在的好奇心,我想提出另一种使用组件的方法。密切注意已包含内容的内容,如果所需元素位于当前组件中,则应使用ViewChild装饰器将其选中。否则,如果它在子组件中,请使用ContentChild装饰器。

// html
<mat-horizontal-stepper ...>
  <mat-step ...>
    <form ...>
      ...
      <div #myMapRef id="map"></div>
      ...
    </form>
  </mat-step>
  ...
</mat-horizontal-stepper>

// parent ts
@ContentChild('myMapRef') // <-- if it's in a child component, your case should use this
@ViewChild('myMapRef') // <-- if it's in this component, your "this is working" would use this
myMap: ElementRef;

ngAfterViewInit() {
  console.log(this.myMap); // can get the ID from the ElementRef
}

我强烈建议您实际熟悉组件生命周期的深度。这是我希望在学习Angular时做的一件事。