typescript - Ionic 2 document.getElementById 返回 null

标签 typescript ionic2

我正在使用 Ionic 2 创建一个小应用程序。现在我正在使用 ionic serve 在浏览器中测试它。在我的 map.html 文件中,我有以下代码:

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

控制台输出:

从 dom 准备好平台 无效的

绞尽脑汁还是找不到它找不到那个元素的原因。

如有任何帮助,我们将不胜感激!

最佳答案

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

为此,我将编写如下代码。

在你的 map.html 中

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

在你的 map.ts 中

make sure you import ViewChild from @angular/core

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
  }

}

关于typescript - Ionic 2 document.getElementById 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43882805/

相关文章:

angular - 搜索字段失去焦点

android - Ionic2/3 angular google maps TypeError : Object(. ..) 不是新 FitBoundsService 的函数

angular - 如何轻松地将 typescript 变量与 html 标记中的字符串连接起来?

typescript 多文件命名空间导出错误

javascript - Angular 6 - 如何等待通话订阅

typescript - Typescript 中枚举值的 Symbol.iterator

angular - 调用服务 angular2 错误 'Property ' 然后'在类型 'Subscription' 上不存在

ionic2 - 警报消息上的新行

javascript - 使用 Ionic 3 从 JSON 数据筛选器的搜索栏

javascript - 如何在 Angular/TypeScript UI 中显示从后端接收到的 Java map 数据?