繁体   English   中英

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

[英]Angular 4 cannot read property nativeElement of undefined using ViewChild

我只是试图访问我的 Angular 4 模板中的一个元素来放置一个谷歌地图,但我不断收到“无法读取未定义的属性本机元素”错误。 我见过其他人问过类似的问题,但到目前为止我尝试过的任何方法都没有奏效。

尝试访问ngOnInitngAfterViewInit的元素时,我遇到了同样的错误。 我也尝试使用document.getElementById并且这也给了我一个空错误。 我知道这不是 Google Maps 错误,因为我在尝试访问 Google Maps 之外的元素时遇到错误。

我在 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的文件。 也许那是你的问题?

我在页面上有一个加载器,它一直在显示,直到页面上的所有数据都返回:

public getData() {
    this.loading = true;
    this.homeService.getData().subscribe(response => {
        this.resort = response;
        this.loading = false;
        this.error = false;
        this.getMap();
    }, error => {
        this.loading = false;
        this.error = true;
    });
}

因此,即使 ngAfterViewInit 正在运行,到该函数运行时,数据库中的数据仍然没有回来,这就是为什么它无法找到元素的原因,因为实际数据从 *ngIf 中隐藏,直到 this.loading是假的。 所以为了纠正我只是在数据返回后调用 getMap() ,而不是在 AfterViewInit 函数中。

然后,我必须将该 getMap 函数包装在 setTimeout 中,以确保 *ngIf 在我尝试访问元素之前也加载了内容数据:

public getMap() {
    setTimeout(() => {
        // accessing element here
    });
 }

也许是因为HomeComponent没有@Component注释?

一方面,没有@Component ,有没有办法HomeComponent知道home.component.html是它的模板,如果它不知道它的模板,它不知道#gmap是视图的孩子。 仅通过命名约定或文件位置将模板与类匹配是不够的。

将类型更改为任何

@ViewChild('gmap') el: any;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM