angular - 角'nativeElement'未定义
问题描述
我正在使用 angular 11.0.1 和 Ionic 5.4.16 并尝试获取 Google 地图。我已经输入了 API 密钥并使用了以下命令
map.page.html
<div #mapElement class="map">
地图.page.ts
import { Component, OnInit, ViewChild } from '@angular/core';
declare var google;
@Component({
selector: 'app-map',
templateUrl: './map.page.html',
styleUrls: ['./map.page.scss'],
})
export class MapPage implements OnInit {
map;
@ViewChild('mapElement') mapElement;
onstructor() {
}
ngOnInit() {
}
ngAfterContentInit() : void
{
this.map = new google.maps.Map (
this.mapElement.nativeElement,
{
center: {lat: -34.397, lng: 150.644},
zoom: 8
}
);
}
}
我收到以下错误。
TypeError:无法读取未定义的属性“nativeElement”
解决方案
如果未指定读取选项,ViewChild 将返回整个组件。所以对你的代码做一点小改动,然后试一试
@ViewChild('mapElement', {read: ElementRef}) private mapElement: ElementRef;
或试试这个
@ViewChild('mapElement', { static: false }) mapElement: ElementRef;
推荐阅读
- r - 改变线性回归中虚拟变量输出的顺序
- python - 如何将多个字典组合成一个更高维度的字典?
- asp.net-core - Azure StorageAccount 中的 Blazor webAssembly 代码
- excel - Excel 函数可将 X 天、x 小时、X 分钟转换为实际分钟数
- spss - 在 spss 的输出中没有得到拟合优度测试
- python - 解压到 Python 中的列表追加方法
- c++ - C++ 两个对象持有指向同一数组不同部分的指针
- bash - 未找到 Gitlab CI/CD Gradle Clean 构建文件
- javascript - 将嵌套的对象数组转换为对象
- java - 如果@BeforeEach 方法中抛出异常,@AfterEach 是否仍会运行