首页 > 解决方案 > 角'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”

标签: angularionic-framework

解决方案


如果未指定读取选项,ViewChild 将返回整个组件。所以对你的代码做一点小改动,然后试一试

@ViewChild('mapElement', {read: ElementRef}) private mapElement: ElementRef;

或试试这个

@ViewChild('mapElement', { static: false }) mapElement: ElementRef;

推荐阅读