Search code examples
ngx-leaflet

Accessing Angular component variable via Leaflet marker.on('click', ...)


I'm using ngx-leaflet to render a map in an Angular app. I'm adding markers to a layer with an EventListener on click like so:

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)
  );
});

With onClick being:

onClick(e) {
  this.showQuestion = true;
  console.log('data: ', e);
}

I want the click on a marker to set the showQuestion Boolean to true, but the context of this is not related to the Angular component, but to the Leaflet event.

How can I access the Angular component this instead of the Leaflet this?


Solution

  • The simplest approach is to use bind to create a function with an explicit this context. See the following example:

    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))
      );
    });
    

    In this example, the onClick handler will be invoked with this set to whatever this is referring to when the call to bind is evaluated (I'm assuming from your example it will be the ngx component).