@viewChild return undefined

2019-07-04 01:07发布

问题:

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.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);  
  }

}

console errors

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

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

Thanks in advance

回答1:

You call initMap() in the constructor.

@ViewChild('mapDiv') mapDiv:ElementRef; is not initialized before ngAfterViewInit() is called.