@viewChild返回undefined [英] @viewChild return undefined

查看:849
本文介绍了@viewChild返回undefined的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have checked other answer for this problems but nothing seems helpful so far. I'm trying to display map in ionic 2 app. But When I try to select #map div it returns undefined. Here is the code

page1.html
< div id =map#mapDiv style =height:380px; >< / 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中。

Please tell me where I'm mistaking. I want to select the div so that the map can be shown inside of #map div.

提前致谢

推荐答案

你打电话给 initMap()在构造函数中。

You call initMap() in the constructor.

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

这篇关于@viewChild返回undefined的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆