繁体   English   中英

使用@viewchild 时,无法以角度读取未定义的属性“nativeElement”

[英]Cannot read property 'nativeElement' of undefined in angular when using @viewchild

在我的代码中,我有一个名为 #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函数中被调用。

似乎您正在尝试访问元素时它对 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);
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM