【问题标题】:TypeError: Cannot read property 'nativeElement' of undefined Ionic-v4TypeError:无法读取未定义 Ionic-v4 的属性“nativeElement”
【发布时间】:2019-09-09 10:46:49
【问题描述】:

我正在尝试这个example,在此示例中的第 6 步中出现错误。我尝试了一些解决方案,但都不起作用。

page.ts

import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { Geolocation } from '@ionic-native/geolocation/ngx';
import { PlaceDataService } from '../services/place-data.service';
declare var google: any;

@Component({
  selector: 'app-add-marker',
  templateUrl: './add-marker.page.html',
  styleUrls: ['./add-marker.page.scss'],
})
export class AddMarkerPage implements OnInit {

  @ViewChild('map', {static: false}) mapContainer: ElementRef;
  map: any;
  museumData = [];

  constructor(
    private geolocation: Geolocation,
    private placeDataService: PlaceDataService) { }

  ngOnInit() {
    this.museumData = this.placeDataService.getMuseums();
    this.displayGoogleMap();
    this.getMarkers();
  }

  displayGoogleMap() {
    const latLng = new google.maps.LatLng(28.6117993, 77.2194934);

    const mapOptions = {
      center: latLng,
      disableDefaultUI: true,
      zoom: 4,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    this.map = new google.maps.Map(this.mapContainer.nativeElement, mapOptions);
  }

  getMarkers() {
    // tslint:disable-next-line:variable-name
    for (let _i = 0; _i < this.museumData.length; _i++) {
      if (_i > 0) {
        this.addMarkersToMap(this.museumData[_i]);
      }
    }
  }

  addMarkersToMap(museum) {
    const position = new google.maps.LatLng(museum.latitude, museum.longitude);
    const museumMarker = new google.maps.Marker({ position, title: museum.name });
    museumMarker.setMap(this.map);
  }

}

page.html

<ion-header>
  <ion-toolbar>
    <ion-buttons slot="start">
      <ion-back-button></ion-back-button>
    </ion-buttons>
    <ion-title>Museum in India</ion-title>
  </ion-toolbar>
</ion-header>

<ion-content class="ion-padding">
  <div #map id="map"></div>
</ion-content>

请帮忙

【问题讨论】:

  • 尝试将 this.displayGoogleMap() 和其他方法放在 ionViewDidLoad() 方法中,而不是 ngOnInit();

标签: angular ionic4


【解决方案1】:

您应该在此处将静态标记为“真”:

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

之后,您的代码就可以正常工作了。

会是:

@ViewChild('map', {static: true}) mapContainer: ElementRef;

【讨论】:

  • 谢谢你,我的朋友!你节省了我的时间!
【解决方案2】:

对我来说,问题是我尝试在构造函数中引用 nativelement。我使用离子 5,但与 4 相同。 将代码移动到 ionViewDidEnter() 用 static:false 解决它。 对你来说,解决方案是:

ngOnInit() {
    
}
ionViewDidEnter(){
   this.museumData = this.placeDataService.getMuseums();
   this.displayGoogleMap();
   this.getMarkers();
}

【讨论】:

  • 太棒了。节省了我的时间。
猜你喜欢
  • 1970-01-01
  • 2018-02-26
  • 1970-01-01
  • 2020-12-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-15
  • 2017-09-28
  • 1970-01-01
相关资源
最近更新 更多