document.getElementById return null


#1

I am creating a small app with Ionic 2. Now I am testing it in browser with ionic serve. In my map.html file, I have following codes:

<ion-content >
   <div  id="myMap"></div>
</ion-content>

In my map.ts file, I tried to this:
this.platform.ready().then((readySource) => {
console.log(‘Platform ready from’, readySource);
console.log(document.getElementById(‘myMap’));
//this.initializeMap();
});

The console outputs:
Platform ready from dom
null

Scratch my head a lot but still can’t find why it can’t locate that element.
Any help would be appreciated!


#2

Because the dom is not yet ready. It’s just the platform. use ionViewDidEnter event handler.

ionViewDidEnter(){
    console.log(document.getElementById('myMap'))
}

#3

You really should not be directly accessing the DOM in an Angular app. That’s Angular’s sphere of control.


#4

Thanks for the help! It works. So here is my further question: why can’t I put ionViewDidEnter in platform.ready? What is the relationship between these two or sequence of loading pages?

:+1:


#5

ionViewDidEnter is a specific ionic lifecycle event, bound to an ionic Page component. You can read about those events over here:

http://blog.ionic.io/navigating-lifecycle-events/

platform.ready should be used on devices. It makes sure you don’t execute any device explicit code before the app is ready for it. You could use platform.ready() inside ionViewDidEnter (which makes more sense), not the other way around.

As @rapropos you should not directly access DOM elements inside your app. It’s completely unnecessary in your case as well. Just grab the ViewChild of your map if you need the instance in your TS class (platform agnostic approach, as Angular2 is meant to be used). Plenty of tutorials on Google Maps and Ionic2 on the internet out there. Just check this excellent tutorial out to get you up and running:


#6

This is beautiful. Funny thing is I followed this book Mobile App Development with Ionic 2 to do this google map thing. His code is here: https://github.com/chrisgriffith/Ionic2Parks/tree/Final/src/pages/park-map

Again, thanks a lot for your help and this really helps me learn Ionic!


#7

Auch… maybe the book explains why he directly accesses the dom like he does :wink: It isn’t good practice though.