我只是想访问我的 Angular 4 模板中的元素以放置 Google map ,但我不断收到“无法读取未定义的属性 native 元素”错误。我见过其他人问过类似的问题,但到目前为止我所做的一切都没有奏效。
尝试访问 ngOnInit
和 ngAfterViewInit
中的元素时出现相同的错误。我还尝试使用 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/