gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 02:38:38 25 4
gpt4 key购买 nike

我读过有关 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com