Morris Hudson Morris Hudson - 1 year ago 292
AngularJS Question

@viewChild return 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

div it returns undefined. Here is the code

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


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

import { NavController } from 'ionic-angular';

declare var google;

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

constructor(public navCtrl: NavController) {

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

{ = 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 '' + zoom + "/" + coord.x + "/" + coord.y + ".png?token=_TOKEN_ID_";
name: "Air Quality",


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

Thanks in advance

Answer Source

You call initMap() in the constructor.

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download