首页 > 解决方案 > DivIcon 内的 Leaflet Angular 组件

问题描述

DivIcon 采用 html: string 参数,我目前将很多 html 连接为字符串,以呈现一个 divIcon,该 divIcon 显示不同的信息,通过 api 的 3 秒轮询刷新。

我需要添加更多信息/样式,并且我的字符串连接开始变得非常大并且很难正确地 css。我想将其更改为更清洁的方式。

1:我找不到任何解决方法来将组件用于 DivIcon。

2:我设法提取了一个角度组件的innerHTML,但是当我添加动态@input()时,提取的HTML不包含任何动态数据,它只是提取了基本模板。(使用 ComponentFactory 和 ComponentRef.createComponent() )

3:我要尝试的最后一个选项是实例化隐藏组件,然后 getDocumentById 它并从中提取纯 HTML。

https://leafletjs.com/reference-1.4.0.html#divicon

标签: angularleaflet

解决方案


好吧,我用选项 1 解决了这个问题,我找到了一个解决方法。

我有选项 3 工作(实例化隐藏组件并从中提取纯 HTML),但后来我发现 Marker 有一个我可以使用的 getElement() 方法,它允许我在 DOM 中获取他的 HTMLElement。

所以我绕过了 DivIcon,我只是动态地实例化了我的组件并将其附加到我的标记 HTMLElement 中,这工作正常,不再需要担心 DivIcon。

  constructor(
      private componentFactoryResolver: ComponentFactoryResolver,
      private rendererFactory: RendererFactory2,
  ) {
      this.renderer = rendererFactory.createRenderer(null, null);
  }

    public appendPopupComponentRef(bus: BusDetails,
                               externalConfig: ExternalConfig,
                               el: HTMLElement,
                               vwcRef: ViewContainerRef): void {
    const factory: ComponentFactory<BusCardComponent> = this.componentFactoryResolver.resolveComponentFactory(BusCardComponent);
    const componentRef = vwcRef.createComponent(factory);

    // Custom it using his @Input()
    componentRef.instance.busDetails = bus;
    componentRef.instance.externalConfig = externalConfig;

    // Render popupComponent HTML inside the DOM's marker HTMLElement
    this.renderer.appendChild(el, componentRef.location.nativeElement);
}

其中 el 是我的 marker.getElement(); (您需要将标记放在图层内才能定义他的 HTMLElement)

其中 vwcRef 是根 viewContainer。

你需要constructor(public viewRef: ViewContainerRef) {}在你的 AppComponent

和这个:

constructor(private appRef: ApplicationRef) {
    this.vwcRef = (appRef.components[0].instance as AppComponent).viewRef;
}

推荐阅读