DOM对象存在后,在angular2组件中初始化传单映射

时间:2017-02-23 23:41:36

标签: angular leaflet angular-material2

我目前正在尝试在角度材料2 tab-group内创建传单地图,如下所示

import {Component, NgModule} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
import { MaterialModule } from '@angular/material';

import { Component, OnInit, OnDestroy } from '@angular/core';
import 'leaflet';

@Component({
  selector: 'minimap',
  template: `<div #minimap [id]="id" class=leaflet-map></div>`
})
export class MiniMap implements OnInit, OnDestroy {
  map: L.Map = null;
  id: string;

  constructor() { 
    this.id = "map" + Date.now();
  }

  ngOnInit() {
    this.map = L.map(this.id).setView([54.5, -115.0], 13);
    L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
      maxZoom: 18,
      attribution:
      '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
    }).addTo(this.map);
  }

  ngOnDestroy() { }
}

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Hello {{name}}</h2>
      <md-tab-group>
      <md-tab label="tab 1">
      tab 1 content
      </md-tab>
      <md-tab label="tab 2">
      tab 2 content
      </md-tab>
      <md-tab label="map tab">
      <minimap></minimap>
      </md-tab>
      </md-tab-group>
    </div>
  `,
})
export class App {
  name:string;
  constructor() {
    this.name = 'Angular2'
  }
}

https://plnkr.co/edit/dLwhv3XoMWMYFkqztkuR?p=preview

不幸的是,当它试图在组件中创建地图时,它会抛出一个错误,说明地图容器还没有存在。我的解释是代码当前在创建DOM对象之前运行。

创建地图的正确方法是什么,以便在DOM对象存在时调用代码?

1 个答案:

答案 0 :(得分:2)

看起来直接引用地图容器元素(通过@ViewChild)工作没有问题。

import {Component, ViewChild} from '@angular/core';
import 'leaflet';

@Component({
    selector: 'minimap',
    template: `<div #mapDiv></div>`
})
export class MiniMap implements OnInit {
    @ViewChild('mapDiv') mapContainer;

    ngOnInit() {
        this.map = L.map(this.mapContainer.nativeElement);
    }
}

更新了Plunk:https://plnkr.co/edit/HGWb3J1f5HL8shFW9EUN?p=preview

但是,一旦显示选项卡(至少第一次),您似乎需要重新初始化地图大小。见Data-toggle tab does not download Leaflet map