javascript - 动态添加 Angular 组件到新的 html 元素

标签 javascript angular google-maps

我读过有关 ViewContainerRef、ComponentFactoryResolver 的内容。

基本上:

  1. 将标签放入 html 中

  2. 在您的 ts 中声明以下内容: @ViewChild('parent', { 读取: ViewContainerRef }) 父级:ViewContainerRef;

  3. 使用以下方式实例化您的组件: const childComponent = this.componentFactoryResolver.resolveComponentFactory(ChildComponent ); this.parent.createComponent(childComponent);

但是,它不适用于页面加载时 html 中已存在的情况。

问题是我使用的是使用 google map api 生成的弹出窗口(当您单击 map 上的某个位置时出现的弹出窗口)。

我需要在弹出窗口出现后放置 div 父标签

var infowindow = new google.maps.InfoWindow({
      // content: this.contentString
      content: " <div #parent></div>"
    });

因此我尝试将其绑定(bind)到弹出窗口的 onclick 事件中,如下所示:

  marker.addListener('click', () => {
        infowindow.open(this.map, marker);
        const childComponent = this.componentFactoryResolver.resolveComponentFactory(CentreDetailsComponent);
        this.parent.createComponent(childComponent);
      });

但是,按照屏幕截图,它不起作用。是因为页面加载时没有生成 div 父标签吗?有人可以帮忙吗?谢谢 enter image description here

最佳答案

最好的解决方案是。你只需选择 AgmCore

npm install --save @agm/core

为此,您需要在 ngModule 中添加核心模块,如下所示:

import { AgmCoreModule } from '@agm/core';
@NgModule({
    imports: [
        AgmCoreModule.forRoot({
            apiKey: 'api_key_googlemap'
          })
    ]})

你的 html View 文件将如下所示

 <div  style="height: 700px; width: 100%;">
    <agm-map [latitude]="32.02" [longitude]="52.2" [zoom]="17">
        <agm-marker   [latitude]="52.2" [longitude]="32.02"   title="Name" >
           <agm-info-window  [isOpen]="true"  >
              <h6>Name</h6>
           </agm-info-window>                                                   
         </agm-marker>                
       </agm-map>
</div>

如果你想要标记中的点击功能

<agm-marker (markerClick)="yourClickFunction()"></agm-marker>

希望这能解决您的问题。

关于javascript - 动态添加 Angular 组件到新的 html 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47717211/

相关文章:

angularjs - Angularjs 中的 Google map 中应用 map 标记后的灰色瓷砖

android 位置监听器不工作?

javascript - 为什么 parseJSON 将我的 JavaScript 对象包装在一个新对象中?

javascript - 响应式设计 - 宽表

javascript - http-proxy-middleware,如何复制所有/cookie header

css - angular SSR 引导应用程序时如何防止 css 动画再次出现

javascript - Extjs KeyMap 不作用于defaultEventAction,而是执行默认的浏览器操作

javascript - Angular 4 - 使用 Enter 关注下一个元素

javascript - textarea resize 在 IE 中不起作用,我想在 IE 中调整大小,它在 chrome 中工作

google-maps - Google Places API未返回place_id