我试图创建一个标记,点击弹出,到目前为止,问题是,当我试图将弹出的内容设置为我的自定义标记时,例如
let popup = new mapboxgl.Popup()
.setHTML("<custom-tag></custom-tag>") 我知道setDOMContent的选择,但我没能把它做好.它应该使用document.createElement(‘定制标签’),因此如果您可以帮助我如何使用自定义组件。谢谢你的帮助!
发布于 2019-02-06 19:46:17
我能够让这个使用角度ComponentFactoryResolver来工作。这里有一些设置,但是一旦运行起来,您就可以使用它来呈现任何您想要的组件(并将它放在任何地方,您可以在任何地方like...including一个mapbox弹出窗口)。
我不确定这是否仍然是这样做的“正确”方式(我仍然在角v5),但它确实有效。
1)创建动态组件服务(不记得我在哪里得到了this...sorry,不管您是谁)
import { Injectable, Injector, ApplicationRef, ComponentFactoryResolver, ComponentRef, Type } from '@angular/core'
@Injectable()
export class DynamicComponentService {
private compRef: ComponentRef<any>;
constructor(private injector: Injector,
private resolver: ComponentFactoryResolver,
private appRef: ApplicationRef) { }
public injectComponent<T>(component: Type<T>, propertySetter?: (type: T) => void): HTMLDivElement {
// Remove the Component if it Already Exists
if (this.compRef) this.compRef.destroy();
// Resolve the Component and Create
const compFactory = this.resolver.resolveComponentFactory(component);
this.compRef = compFactory.create(this.injector);
// Allow a Property Setter to be Passed in (To Set a Model Property, etc)
if (propertySetter)
propertySetter(this.compRef.instance);
// Attach to Application
this.appRef.attachView(this.compRef.hostView);
// Create Wrapper Div and Inject Html
let div = document.createElement('div');
div.appendChild(this.compRef.location.nativeElement);
// Return the Rendered DOM Element
return div;
}
}2)使用服务在mapbox-gl弹出窗口中呈现自定义组件。
import { MyCustomMapboxPopup } from "../app/components/my-custom-mapbox-popup.component"
import { DynamicComponentService } from "../services/dynamic-component";
...
// Inside a map.on("click") or wherever you want to create your popup
// Inject Component and Render Down to HTMLDivElement Object
let popupContent = this.dynamicComponentService.injectComponent(
MyCustomMapboxPopup,
x => x.model = new PopupModel()); // This Is where You can pass
// a Model or other Properties to your Component
new mapboxgl.Popup({ closeOnClick: false })
.setLngLat(...wherever you want the popup to show)
.setDOMContent(popupContent)
.addTo(map);
...为了避免任何混淆,自定义弹出组件看起来可能如下所示:
import { Component } from '@angular/core';
@Component({
selector: "custom-mapbox-popup",
templateUrl: "./my-custom-mapbox-popup.component.html"
})
export class MyCustomMapboxPopup {
public model: PopupModel; // Model Property
}
// HTML
<div class="my-custom-popup">
<div *ngIf="model">
<h3>{{this.model.SomeModelProperty}}</h3>
</div>
</div>https://stackoverflow.com/questions/48229709
复制相似问题