我正在使用ngx叶来渲染Angular应用中的地图。我正在使用EventListener在单击时将标记添加到一层中:
questions.forEach((question) => {
this.layers.push(
marker([question.lat, question.lng], {
icon: icon({
iconSize: [25, 41],
iconAnchor: [13, 41],
iconUrl: 'assets/marker-icon.png',
shadowUrl: 'assets/marker-shadow.png'
})
}).on('click', this.onClick)
);
});
与OnClick为:
onClick(e) {
this.showQuestion = true;
console.log('data: ', e);
}
我希望单击标记将showquestion boolean设置为true,但是this
的上下文与角组件无关,而与传单事件有关。
如何访问角组件this
而不是传单this
?
最简单的方法是使用绑定来使用显式this
上下文创建功能。请参阅以下示例:
questions.forEach((question) => {
this.layers.push(
marker([question.lat, question.lng], {
icon: icon({
iconSize: [25, 41],
iconAnchor: [13, 41],
iconUrl: 'assets/marker-icon.png',
shadowUrl: 'assets/marker-shadow.png'
})
}).on('click', this.onClick.bind(this))
);
});
在此示例中,将使用this
设置为this
何时评估绑定的呼叫(我假设您的示例将是NGX组件)。