Angular2 click listener for Mapboxgl function

When working with a mapboxgl map click listener in an Angular2 component, I encountered an issue regarding accessing variables outside of the click function. Despite my efforts, using this.something did not work as expected. It seems to be a scope problem specific to mapboxgl. Here is a simplified version of the problem where the console prints out undefined...


public map: Map;
public test: string = 'test'; 

initialize() {
    this.map.on('click', clickListener);
}

clickListener() {
    console.log(this.test); // undefined
}

Answer №1

In order to address the issue, it is important to pass the event to the function. My solution to the same problem was as follows:

this.map.on('click', (event: any) => {
    const markers = this.map.queryRenderedFeatures(event.point, {layers: ['markers']})
    if (markers.length) {
        console.log(markers)
    }
})

Answer №2

Consider the following approach:

let myMap: Map;
let testValue: string = 'testing';

function initialize() {
    myMap.on('click', handleClick.bind(this));
}

function handleClick() {
    console.log(testValue); // will output 'testing'
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The Primeng badge feature fails to detect changes in severity

Within my primeng application, there is an icon featuring a badge that is structured as follows: <i (click)="showAllNotifications()" class="pi pi-bell mr-3 p-text-secondary" pBadge style="font-size: 2rem" [value]=&q ...

In an array where the first 3 images have been filtered using an if statement, how can I show the image at the 3rd index (4th image) starting from the beginning?

In my personal web development project, I'm using AngularJS for the front-end and .NET Core for the back-end to create a website for a musical instrument retailer. The model I'm working with is called "Guitar" and all the guitar data is stored in ...

The element 'mat-toolbar' is unrecognized

I included the following code in app.component.html : <mat-toolbar> Responsive side navigation </mat-toolbar> and I made sure to import MatToolbarModule in app.module.ts import { NgModule } from '@angular/core'; import { BrowserMod ...

Troubleshooting Safari compatibility issues with Twitter Direct Messages in Angular

I am attempting to create a Twitter direct message with predetermined text already filled in. My current method involves using window.open() to prepare the message. window.open(https://twitter.com/messages/compose?text=${this.helloWorld}); helloWorld = ...

Uploading images using Angular and PHP: A comprehensive guide

I am a beginner in Angular and I am having trouble uploading an image from Angular as I encounter 4 errors: 1) Error in the post method: Cannot find name 'formData'. Did you mean 'FormData'?ts(2552) 2) Error in the subscribe method: ...

Implement method functionality within TypeScript interfaces

I've encountered a scenario where I have an interface that will be utilized by multiple classes: interface I { readonly id: string; process(): void; } My objective is to pass the id through a constructor like so: class A implements I {...} let a: ...

What is the advantage of utilizing the "extends" keyword over directly stating the type?

Recently, I came across this interesting article at https://www.typescriptlang.org/docs/handbook/generics.html#generic-constraints I can't help but wonder why the extends keyword is necessary in this context. interface Lengthwise { length: number; ...

Testing TypeScript using Jasmine and Chutzpah within Visual Studio 2015

I am new to unit testing in AngularJS with TypeScript. I have been using jasmine and chutzpah for unit testing, but I encountered an error "ReferenceError: Can't find variable: angular". My test file looks like this: //File:test.ts ///<chutzpah_r ...

Learning how to merge two observable streams in Angular2 by utilizing RxJS and the powerful .flatMap method

Within my Angular2 app, I have created an Observable in a Service called ContentService. Here is a simplified version of the code: @Injectable() export class ContentService { constructor(private http:Http, private apiService:ApiService) { th ...

Structured similar to a map with typed elements

As a beginner in Typescript, I am delving into creating a typed map structure where the values are associated with specific keys. This can be demonstrated through pseudo JS code without types: const propertyA = "PropertyA"; const propertyB = "PropertyB"; ...

Encountering TS9006 error while working on a Vue2 Vite project with a combination of TypeScript and

I am in the process of updating an older Vue2 webpack (JS) project to Vite, which involves a mix of JS and TS. Additionally, I am transitioning from using Vuex to Pinia. store.ts interface UserLoginRequestI { emailOrUsername?: string; password?: s ...

401 error code for all CRUD operations in the .NET Framework API

So, I've been working on a project that consists of a .Net framework API and an Angular frontend. I recently implemented OWIN JWT authentication, but now I'm encountering a persistent 401 error no matter what I try. I've attempted numerous ...

Set up the user django with standard configuration values

I'm currently working with Django and Angular 2, trying to create a user with default values, but it's not happening as expected... Model class Settings(models.Model): user = models.ForeignKey('auth.User', related_name='setti ...

Insert an HTML element or Angular component dynamically when a specific function is called in an Angular application

Currently, I am working on a component that contains a button connected to a function in the .ts file. My goal is to have this function add an HTML element or make it visible when the button is clicked. Specifically, I would like a dynamic <div> elem ...

Show a notification to the user through a pop-up message when they either select or deselect the checkbox in an Angular application

Suppose the user first selects the value for "Automatic" and then changes it to an unchecked state. An alert message will appear if any of the following accordions are in the "Completed" status. ...

Unable to fetch data from Array using an identifier in Angular 4

My goal is to fetch an object from an array by its id using the getItem() method. import { Injectable } from '@angular/core'; import { Http, Response } from '@angular/http'; import { Observable } from 'rxjs/Observable'; impor ...

What is the best way to create a method that waits for a POST request to complete?

I have the following code snippet: login() { const body = JSON.stringify({ "usuario":"juanma", "password":"1234"}); console.log(body); let tokencito:string = '' const params = ne ...

Is it possible to directly bind a JSON object from a typescript file to an input value in Angular 2?

Here is the code snippet from my .ts file: yourInfoData: IYourInfoData; //IYourInfoData represents the constructor getYourInfoData() { $this = this; $this.yourInfoData = yourInfoDataResponse; //yourInfoDataResponse is the response from the service. } ...

Enumerated type alias in Typescript

Within my typings file, I have the following: declare namespace Somatic { enum PropType { html, object, css } } In a separate file named index.ts, I create a shorter alias for this enum like so: type PropType = Somatic.Pr ...

How can one determine the source of change detection activation in Angular 2?

I just launched a new component and it appears to be causing change detection to occur multiple times per second: // debugging code ngDoCheck() { console.log('DO_CHECK', new Date().toLocaleTimeString()); } Results: https://i.sstatic. ...