【问题标题】:Cannot read property 'nativeElement' of undefined in angular when using @viewchild使用@viewchild 时无法读取角度未定义的属性“nativeElement”
【发布时间】:2020-01-11 02:17:27
【问题描述】:

在我的代码中,我有一个名为 #map 的 div,它将在 for 循环的条件之后显示。

<div *ngFor="let message of fullMessagesArr">
 <div *ngIf="message.replyMap">
   <div #gmap style="width:100px;height:400px"></div>
 </div>
</div> 

下面给出的我的 .ts 文件带有 initMap 函数。

@ViewChild('gmap') gmapElement: ElementRef;
map: google.maps.Map;

  initGMap = () => {
    const mapProp = {
      center: new google.maps.LatLng(6.9404, 79.8464),
      zoom: 15,
      mapTypeId: google.maps.MapTypeId.satellite
    };
    this.map = new google.maps.Map(this.gmapElement.nativeElement, mapProp);
  }

initGMap 函数在 sendMessage 函数内部被调用。

【问题讨论】:

  • fullMessagesArr 设置在哪里?要么未设置,要么为空,要么没有消息获得replyMap 属性集
  • 不,它不为空,我通过 API 调用将项目放入它,它不为空,我检查了
  • 你能给我们看一下代码吗?
  • 错误不在数组中,当我使用@viewchild 并尝试使用 initGMap 函数加载地图时出现问题
  • 可能是同步问题。如果在给 fullMessagesArr 赋值之前调用 initGMap,可能会导致这些问题。控制台中打印的内容可能会产生误导

标签: javascript angular typescript ecmascript-6 single-page-application


【解决方案1】:

似乎您正在尝试访问 DOM 不可见的元素,所以您可以运行 setTimeOut 或使用 ngAfterContentInit 生命周期挂钩来等待 DOM 被渲染

export class AppComponent implements OnInit, OnDestroy, AfterContentInit {

    public ngAfterContentInit(): void {
       const mapProp = {
           center: new google.maps.LatLng(6.9404, 79.8464),
           zoom: 15,
           mapTypeId: google.maps.MapTypeId.satellite
       };
       this.map = new google.maps.Map(this.gmapElement.nativeElement, mapProp);
    }
}

或使用 setTimeOut

initGMap = () => {
    const mapProp = {
      center: new google.maps.LatLng(6.9404, 79.8464),
      zoom: 15,
      mapTypeId: google.maps.MapTypeId.satellite
    };
    setTimeout(() => {
         this.map = new google.maps.Map(this.gmapElement.nativeElement, mapProp);
    }, 3000);
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-04
    • 1970-01-01
    • 1970-01-01
    • 2018-02-26
    • 2017-12-15
    • 2017-09-28
    相关资源
    最近更新 更多