javascript - 使用@viewchild时无法读取 Angular 中未定义的属性 'nativeElement'

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

在我的代码中,我有一个名为 #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 生命周期钩子(Hook)来等待 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);
  }

关于javascript - 使用@viewchild时无法读取 Angular 中未定义的属性 'nativeElement',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57851890/

相关文章:

javascript - d3.js:在 Angular 应用程序和 node.js 上运行相同的代码

node.js - 如何在浏览器关闭时让我的应用程序注销?

javascript - 检查是否选择了某个选项并编辑 HTML 标记

javascript - 无法在 js 生成的表中设置 td 宽度

javascript - 简单的正则表达式替换括号

javascript - 在 svg 中的文本上方绘制路径

javascript/Angular : add 'line break' via string

javascript - 无法访问 Angular 2 中 child 服务的成员

javascript - Object.keys(myObject) 不返回 typescript 中类的属性

html - Angular 2聊天框消息从下到上