如何在Leaflet标记的弹出窗口中生成Angular 4组件?

DAR*_*Guy 7 web-component leaflet angular

我一直是一个很长的Angular 1.x用户,现在我正在使用Angular 4创建一个新的应用程序.我仍然没有掌握大多数概念,但我终于有一些非常好的工作.但是,我有一个问题,我需要使用Leaflet在Marker的弹出窗口中显示Angular 4组件(尽管在1.x中我只是使用了指令).

现在,在Angular 1.x中我可以使用$ compile对模板中的指令(`<component>{{ text }}</component>`)里面的按钮等等它会起作用,但是Angular 4与它的AoT完全不同,并且在运行时编译似乎真的很棒很难,并没有简单的解决方案.

在这里问了一个问题,作者说我可以使用指令.我不确定这是否是正确的方法,甚至不知道如何将我自己的代码与他提出的解决方案混合...所以我做了一个基于npm的小项目,Angular 4和Leaflet已经设置好,以防你知道如何帮助我还是想试一试(我非常感谢!).我一直在敲打这个可能已经一个星期了,我真的厌倦了尝试了很多替代品而没有成功:(

这是我在GitHub中的回购链接:https://github.com/darkguy2008/leaflet-angular4-issue

我们的想法是在Marker中生成PopupComponent(或类似的东西),代码可以在src/app/services/map.service.ts第38行找到.

提前致谢!:)

编辑

我设法解决了:)看到标记答案的细节,或这个差异.有一些警告,Angular 4和Leaflet的程序有点不同,它不需要那么多的变化:https://github.com/darkguy2008/leaflet-angular4-issue/commit/b5e3881ffc9889645f2ae7e65f4eed4d4db6779b

我还从这里解释的解决方案中创建了一个自定义编译服务,并上传到相同的GitHub存储库.谢谢@yurzui!:)

DAR*_*Guy 12

好的,所以感谢@ ghybs的建议,我给了那个链接另一个尝试并设法解决了这个问题:D.Leaflet与谷歌地图略有不同(它也更短),建议的解决方案可能会更小,更容易理解,所以这是我使用Leaflet的版本.

基本上,您需要将弹出组件放在主应用程序模块的entryComponents字段中.关键的东西是,在m.onclick()那里,我们创建一个组件,在a里面渲染它div,然后我们将它div的内容传递给leaflet popup容器元素.有点棘手,但它的工作原理.

我有一些时间并将此解决方案转换为Angular 4的新$ compile.请在此处查看详细信息.谢谢@yurzui!:)

这是核心代码......其他东西(css,webpack等)和OP在同一个repo中,简化为几个文件:https://github.com/darkguy2008/leaflet-angular4-issue但是你只需要这个例子就可以使它工作:

import 'leaflet';
import './main.scss';
import "reflect-metadata";
import "zone.js/dist/zone";
import "zone.js/dist/long-stack-trace-zone";
import { BrowserModule } from "@angular/platform-browser";
import { platformBrowserDynamic } from "@angular/platform-browser-dynamic";
import { Component, NgModule, ComponentRef, Injector, ApplicationRef, ComponentFactoryResolver, Injectable, NgZone } from "@angular/core";

// ###########################################
// App component
// ###########################################
@Component({
    selector: "app",
    template: `<section class="app"><map></map></section>`
})
class AppComponent { }

// ###########################################
// Popup component
// ###########################################
@Component({
    selector: "popup",
    template: `<section class="popup">Popup Component! :D {{ param }}</section>`
})
class PopupComponent { }

// ###########################################
// Leaflet map service
// ###########################################
@Injectable()
class MapService {

    map: any;
    baseMaps: any;
    markersLayer: any;

    public injector: Injector;
    public appRef: ApplicationRef;
    public resolver: ComponentFactoryResolver;
    public compRef: any;
    public component: any;

    counter: number;

    init(selector) {
        this.baseMaps = {
            CartoDB: L.tileLayer("http://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png", {
                attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> &copy; <a href="http://cartodb.com/attributions">CartoDB</a>'
            })
        };
        L.Icon.Default.imagePath = '.';
        L.Icon.Default.mergeOptions({
            iconUrl: require('leaflet/dist/images/marker-icon.png'),
            shadowUrl: require('leaflet/dist/images/marker-shadow.png')
        });
        this.map = L.map(selector);
        this.baseMaps.CartoDB.addTo(this.map);
        this.map.setView([51.505, -0.09], 13);

        this.markersLayer = new L.FeatureGroup(null);
        this.markersLayer.clearLayers();
        this.markersLayer.addTo(this.map);
    }

    addMarker() {
        var m = L.marker([51.510, -0.09]);
        m.bindTooltip('Angular 4 marker (PopupComponent)');
        m.bindPopup(null);
        m.on('click', (e) => {
            if (this.compRef) this.compRef.destroy();
            const compFactory = this.resolver.resolveComponentFactory(this.component);
            this.compRef = compFactory.create(this.injector);

            this.compRef.instance.param = 0;
            setInterval(() => this.compRef.instance.param++, 1000);

            this.appRef.attachView(this.compRef.hostView);
            this.compRef.onDestroy(() => {
                this.appRef.detachView(this.compRef.hostView);
            });
            let div = document.createElement('div');
            div.appendChild(this.compRef.location.nativeElement);
            m.setPopupContent(div);
        });
        this.markersLayer.addLayer(m);
        return m;
    }
}

// ###########################################
// Map component. These imports must be made
// here, they can't be in a service as they
// seem to depend on being loaded inside a
// component.
// ###########################################
@Component({
    selector: "map",
    template: `<section class="map"><div id="map"></div></section>`,
})
class MapComponent {

    marker: any;
    compRef: ComponentRef<PopupComponent>;

    constructor(
        private mapService: MapService,
        private injector: Injector,
        private appRef: ApplicationRef,
        private resolver: ComponentFactoryResolver
    ) { }

    ngOnInit() {
        this.mapService.init('map');
        this.mapService.component = PopupComponent;
        this.mapService.appRef = this.appRef;
        this.mapService.compRef = this.compRef;
        this.mapService.injector = this.injector;
        this.mapService.resolver = this.resolver;
        this.marker = this.mapService.addMarker();
    }
}

// ###########################################
// Main module
// ###########################################
@NgModule({
    imports: [
        BrowserModule
    ],
    providers: [
        MapService
    ],
    declarations: [
        AppComponent,
        MapComponent,
        PopupComponent
    ],
    entryComponents: [
        PopupComponent
    ],
    bootstrap: [AppComponent]
})
class AppModule { }

platformBrowserDynamic().bootstrapModule(AppModule);
Run Code Online (Sandbox Code Playgroud)