我坚持通过事件的对象访问变量。 我可以在这段代码中重构一些东西,因为我需要在我在templateUrl中显示一些注释后,在事件点击地图中设置它们。 这是代码:
import { Component, OnInit, AfterViewInit } from '@angular/core';
declare var ol: any;
@Component({
selector: 'my-map-app',
templateUrl: 'app.component.html'
})
export class AppComponent implements OnInit, AfterViewInit {
static draw: any;
annotations: any[];
constructor() {
this.annotations = [];
}
ngOnInit(): void {
// ADD MAP
AppComponent.map = new ol.Map({
target: 'map',
layers: layers,
view: new ol.View({
center: ol.proj.fromLonLat([10, 10]),
zoom: 2
})
});
// Action when clicking on a Point (no edition mode)
AppComponent.map.on('singleclick', function(evt) {
// here I want to access and set the array of annotations
//this.annotations or AppComponent.annotations is not available
});
}
app.component.html上的编辑:
<select >
<option *ngFor="let annotation of annotations">{{annotation.name}}</option>
</select>
答案 0 :(得分:1)
我用这个特殊问题做了以下事情但是如果有任何精确的解决方案可用,请告诉我
ngOnInit(): void {
let _self:any = this;
AppComponent.map = new ol.Map({
target: 'map',
layers: layers,
view: new ol.View({
center: ol.proj.fromLonLat([10, 10]),
zoom: 2
})
});
// Action when clicking on a Point (no edition mode)
AppComponent.map.on('singleclick', function(evt) {
console.log("this = ",_self);
});
}
答案 1 :(得分:0)
最后经过一整天的挣扎,这就是我必须添加的内容(ChangeDetectorRef):
import { Component, OnInit, AfterViewInit, ChangeDetectorRef } from '@angular/core';
declare var ol: any;
@Component({
selector: 'my-map-app',
templateUrl: 'app.component.html'
})
export class AppComponent implements OnInit, AfterViewInit {
static draw: any;
static reload: any;
annotations: any[];
constructor(private changeDetectorRef: ChangeDetectorRef) {
AppComponent.reload = changeDetectorRef;
this.annotations = [];
}
ngOnInit(): void {
let _self: any = this; //from @anshuVersatile
// ADD MAP
AppComponent.map = new ol.Map({
target: 'map',
layers: layers,
view: new ol.View({
center: ol.proj.fromLonLat([10, 10]),
zoom: 2
})
});
AppComponent.map.on('singleclick', function(evt) {
self.annotations = ['foo', 'bar'];
AppComponent.reload.detectChanges(); //this is what i had to trigger
});
}
感谢@anshuVersatile - 如果有人找到更好的东西,请告诉我们!!