You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular用@ViewChild按模板名获取MapInfoWindow调用open方法报错

问题原因

你使用模板引用变量作为@ViewChild选择器时,Angular默认返回的是<map-info-window>标签对应的原生DOM元素实例,不是Angular官方@angular/google-maps封装的MapInfoWindow组件类实例,原生DOM对象自然不存在open方法,因此触发类型错误。
而你直接传入MapInfoWindow类作为选择器时,@ViewChild会自动匹配页面中对应的Angular组件实例,返回的就是带open方法的正确对象,因此运行正常。


两种解决方案

方案1:修改模板引用的导出指向

MapInfoWindow组件内置的exportAs名称为mapInfoWindow,你可以在模板中显式指定模板引用指向组件实例而非DOM元素:

<map-info-window #myInfoWindow="mapInfoWindow">
  <!-- 自定义内容 -->
</map-info-window>

此时TS代码中原有@ViewChild('myInfoWindow')无需额外修改,就能拿到正确的MapInfoWindow实例。

方案2:给@ViewChild添加read参数指定读取类型

不需要修改模板,直接在TS的@ViewChild配置中添加read参数,明确告知Angular需要从匹配节点中读取MapInfoWindow组件实例:

@ViewChild('myInfoWindow', { static: false, read: MapInfoWindow }) myMapInfoWindow: MapInfoWindow;

验证方法:修改完成后在openInfo方法中打印this.myMapInfoWindow,确认输出为MapInfoWindow类实例而非HTMLElement类型即可。

内容的提问来源于stack exchange,提问作者Santa Paws

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 21:21:03