我认为您遇到了上下文问题。在执行渲染模板时,this
inside的值为 null。getcustomcontent
有一些选项可以设置函数的执行上下文。在下面的示例中,我使用的是bind
.
popupTemplate: {
content: this.customPopupFunction.bind(this) // <- here
}
基本上,我表示何时customPopupFunction
调用它应该绑定到组件。这就是this
函数内部起作用的原因,它madeBy
在弹出模板内容中呈现组件的属性。
Mozilla Docs - 绑定
import { Component, OnInit, OnDestroy, ViewChild, ElementRef } from "@angular/core";
import { loadModules } from "esri-loader";
@Component({
selector: 'app-esri-map',
templateUrl: './esri-map.component.html',
styleUrls: ['./esri-map.component.scss']
})
export class EsriMapComponent implements OnInit, OnDestroy {
@ViewChild("mapViewNode", { static: true }) private mapViewEl: ElementRef;
view: any;
// to keep loaded esri modules
esriModules = {
layers: {
FeatureLayer: null
}
};
madeBy = '@cabesuon';
constructor() {}
async initializeMap() {
try {
// Load the modules for the ArcGIS API for JavaScript
const [
Map,
MapView,
FeatureLayer
] = await loadModules([
"esri/Map",
"esri/views/MapView",
"esri/layers/FeatureLayer"
]);
// save the modules on a property for later
this.esriModules.layers.FeatureLayer = FeatureLayer;
// Create the FeatureLayer
// USA counties layer
var countiesLayer = new FeatureLayer({
portalItem: {
id: "cd13d0ed1c8f4b0ea0914366b4ed5bd6"
},
outFields: ["*"],
minScale: 0,
maxScale: 0,
popupTemplate: {
content: this.customPopupFunction.bind(this)
}
});
// Configure the Map
const mapProperties = {
basemap: "streets",
layers: [countiesLayer]
};
const map = new Map(mapProperties);
// Initialize the MapView
const mapViewProperties = {
container: this.mapViewEl.nativeElement,
map,
zoom: 5,
center: [-107.3567, 37.7705]
};
this.view = new MapView(mapViewProperties);
await this.view.when(); // wait for map to load
return this.view;
} catch (error) {
console.error("EsriLoader: ", error);
}
}
ngOnInit() {
this.initializeMap().then(_ => {
// The map has been initialized
console.log("mapView ready: ", this.view.ready);
});
}
ngOnDestroy() {
if (this.view) {
// destroy the map view
this.view.container = null;
}
}
customPopupFunction(feature) {
return `<p>This is <strong>${feature.graphic.attributes.NAME}</strong> county, state of <strong>${feature.graphic.attributes.STATE_NAME}</strong></p>` +
`<p>This is an example of a custom popup content made by <span style="color:blue;">${this.madeBy}</span></p>`;
}
}