javascript - Angular 4 无法使用 ViewChild 读取未定义的属性 nativeElement

标签 javascript angular google-maps

我只是想访问我的 Angular 4 模板中的元素以放置 Google map ,但我不断收到“无法读取未定义的属性 native 元素”错误。我见过其他人问过类似的问题,但到目前为止我所做的一切都没有奏效。

尝试访问 ngOnInitngAfterViewInit 中的元素时出现相同的错误。我还尝试使用 document.getElementById ,这也给了我一个空错误。我知道这不是 Google map 错误,因为我在尝试访问 Google map 之外的元素时遇到错误。

我在 home.component.ts 中有以下内容(这是在特定的 home 组件中,而不是在主应用程序模块中):

import { NgModule, Component, OnInit, AfterViewInit, ElementRef, ViewChild } from '@angular/core';
import { } from '@types/googlemaps';

@Component({
   selector: 'home-page',
   templateUrl: './home.html'
})

export class HomeComponent implements OnInit, AfterViewInit {
     @ViewChild('gmap') el:ElementRef;
     map: google.maps.Map;

     public ngOnInit() {
        // other component initialization code here
     }

     public ngAfterViewInit () {
        let mapProp = {
           center: new google.maps.LatLng(18.5793, 73.8143),
           zoom: 15,
           mapTypeId: google.maps.MapTypeId.ROADMAP
         };
         this.map = new google.maps.Map(this.el.nativeElement, mapProp);

      // this alone gives me the same error
      setTimeout(() => {
          console.log(this.el.nativeElement);
       }, 0);
    }
}

在组件模板内 - home.component.html:

<div class="row">
    <div class="col-md-12">
        <div class="text-center">
            <div #gmap style="width:100%;height:400px"></div>
        </div>
    </div>
</div>

最佳答案

您的组件的 templateUrl 显示为 './home.html' 但您还在“组件模板内部 - 中提到文件名为 home.component.html >home.component.html”。也许这是你的问题?

关于javascript - Angular 4 无法使用 ViewChild 读取未定义的属性 nativeElement,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49142176/

相关文章:

angular - ngFor 索引加 1 或计数加 1

angular - 类型错误 : Cannot read property 'subscribe' of undefined in unit test

html - 具有相同 Controller 和相同模板的多个选项卡上的 Angular Google map

ruby-on-rails - Ruby on Rails、form_remote_tag 和 Google Maps API

javascript - jQuery 使用空元素检查是否存在

javascript - AngularJS 组件 - 带有 Typescript 的 ngModelController

javascript - 获取流的内容长度

javascript - 通过提交按钮将 PHP 转换为 JavaScript

angular - Ionic 2 auth - 如果本地存储上有用户,则跳过登录页面

android - 在Android中的recylerview上实现 map 时,Google Map返回空对象引用