【问题标题】:@viewChild return undefined@viewChild 返回未定义
【发布时间】:2017-03-11 00:50:29
【问题描述】:

我已经检查了这个问题的其他答案,但到目前为止似乎没有任何帮助。我正在尝试在 ionic 2 应用程序中显示地图。但是当我尝试选择#map div 时,它返回未定义。这是代码

page1.html <div id="map" #mapDiv style="height:380px;"></div>

page1.ts

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

import { NavController } from 'ionic-angular';

declare var google;

@Component({
  selector: 'page-page1',
  templateUrl: 'page1.html',
})
export class Page1 implements AfterViewInit {
    @ViewChild('mapDiv') mapDiv:ElementRef;
    map;
    t;

  constructor(public navCtrl: NavController) {
    this.initMap();
  }

  ngAfterViewInit(){
    console.log('My element: ' + this.mapDiv);
  }

  initMap()
  {
     this.map = new google.maps.Map(this.mapDiv.nativeElement,  {  
                  center:  new  google.maps.LatLng(51.505,  -0.09),  
                  mapTypeId:  google.maps.MapTypeId.ROADMAP,  
                  zoom:  11  
              });  

    this.t = new Date().getTime();  
      var  waqiMapOverlay  =  new  google.maps.ImageMapType({  
                  getTileUrl:  function(coord,  zoom)  {  
                            return  'http://tiles.aqicn.org/tiles/usepa-aqi/'  +  zoom  +  "/"  +  coord.x  +  "/"  +  coord.y  +  ".png?token=_TOKEN_ID_";  
                  },  
                  name:  "Air  Quality",  
        });  

      this.map.overlayMapTypes.insertAt(0,waqiMapOverlay);  
  }

}

控制台错误

`Error in ./Page1 class Page1_Host - inline template:0:0 caused by: Cannot read property 'nativeElement' of undefined`

请告诉我我在哪里弄错了。我想选择 div 以便地图可以显示在 #map div 内。

提前致谢

【问题讨论】:

标签: angular ionic-framework ionic2


【解决方案1】:

你在构造函数中调用initMap()

@ViewChild('mapDiv') mapDiv:ElementRef; 在调用ngAfterViewInit() 之前未初始化。

【讨论】:

  • 非常感谢。我还在学习。这解决了我的问题。惊人的。再次感谢。
猜你喜欢
  • 2023-03-21
  • 2019-10-03
  • 2018-05-14
  • 2018-10-25
  • 2019-10-19
  • 2017-01-08
  • 2019-07-28
  • 2020-03-25
  • 2016-04-29
相关资源
最近更新 更多