2017-05-10 86 views
2

我正在用Ionic 2创建一个小应用程序。现在我正在使用离子服务器在浏览器中测试它。在我map.html文件,我有以下代码:Ionic 2 document.getElementById返回null

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

在我map.ts文件,我试着这样做:

this.platform.ready().then((readySource) => { 
console.log('Platform ready from', readySource); 
console.log(document.getElementById('myMap')); 
//this.initializeMap(); 
}); 

控制台输出:

Platform ready from dom null

我搔搔头很多,但仍然无法找到为什么它不能找到该元素。

任何帮助,将不胜感激!

回答

4

如果您试图获取id的元素库,您可以使用angular的viewChild而不是使用javascript。

要做到这一点,我会写这样的代码。

在你map.html

<ion-content > 
    <div #myMap></div> 
</ion-content> 

在你map.ts

确保你从@角/核心导入ViewChild

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

... 

export class MapPage { 
    @ViewChild('myMap') myMap ; 

    constructor(public viewCtrl: ViewController, params: NavParams) { 
    console.log(this.myMap); //visit your element by using this.myMap 
    } 

} 
+1

感谢您的帮助。这就像一个魅力。 –

+0

在我的情况下,我有动态离子网格,我必须访问ion-col。使用上面的代码this.myMap返回null – amy

相关问题