In Typescript, the use of an array as a class member is not defined

I'm having trouble adding an array as a class member in my Typescript code. When I try to access it in a certain function, I keep getting an error saying it's undefined. What am I doing wrong?

.html

<button id="storePersonBtn">

.ts

export class App {

    public myArray: Array<Boolean> = [];

    constructor() {
        console.log(this.myArray) //logs []
        $('#storePersonBtn').click(this.storePerson);
    }

    private storePerson() {
        console.log(this.myArray) //logs undefined
    }
}

Answer №1

The issue at hand lies in the concept of JavaScript's this being bound at the call site. When you directly call a.b(), the this inside function b will refer to object a. However, when you separate the function into a variable like this:

const b = a.b;
b();

In this scenario, the this inside function b becomes undefined.

The recommended approach is to utilize an arrow function like in this example:

.click(() => this.storePerson())

By using this method, you ensure that storePerson is invoked with the correct this context.

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

Using Typescript with React functional components: the proper way to invoke a child method from a parent function

My current setup is quite simple: <Page> <Modal> <Form /> </Modal> </Page> All components mentioned are functional components. Within <Modal />, there is a close function defined like this: const close = () => ...

Submitting Data in Ionic 3 using Http Post and Storing in Sqlite with Angular 4

I am facing an issue while trying to post an array of contacts on a WebService. When I send the array, the data appears as NULL in the WebService response. I am confused about how to use Let params{} The error message shows "object undefined". Addition ...

What could be causing the issues with SSL certificates when using Node.js/Express-TypeScript?

I'm currently in the process of transitioning a project's backend from JavaScript (Node.js/Express) to TypeScript. However, I've encountered an unusual issue where FS's readFileSync is unable to access the key.pem or cert.pem files in t ...

Navigating through different components in Angular 4 using a service for routing

Encountering an issue while connecting my Angular 4 and REST application with a service. Here's the error message: compiler.es5.js:1694 Uncaught Error: Can't resolve all parameters for TypeaheadComponent: (?, [object Object], [object Object]). ...

What is the relationship between Typescript references, builds, and Docker?

I am facing a dilemma with my projectA which utilizes a common package that is also needed by my other Nodejs services. I am unsure of the best approach to package this in a Docker file. Ideally, running tsc build would compile both the project and the dep ...

Functions have been successfully deployed, but they are not appearing on the Azure Portal

I am experiencing difficulties deploying basic Typescript functions to Azure. Despite a successful deployment using VS code and confirmation in the Output window, I cannot see any functions listed in the Azure Portal under the Function App: https://i.stac ...

Charts are not displaying properly in Angular 10 when using ng2-charts

My application is supposed to display charts, but for some reason, the charts are not loading. When I check the DOM, I see the element being created with ==$0, which is confusing to me. I am using Angular Material, but I don't think that should be a ...

Is it possible to access the service and 'self' directly from the HTML template?

When working with Angular 6, one method to access component properties from a service is to pass 'self' to the service directly from the component. An example of this implementation is shown below: myComponent.ts public myButton; constructor(p ...

A step-by-step guide on effectively adopting the strategy design pattern

Seeking guidance on the implementation of the strategy design pattern to ensure correctness. Consider a scenario where the class FormBuilder employs strategies from the following list in order to construct the form: SimpleFormStrategy ExtendedFormStrate ...

The language translation in Angular 6 remains static and unchanged until the page is refreshed

My website supports 5 different languages with English as the default. When I switch languages in the header component... header.component.ts onSetLanguage(lang: string) { this.trans.use(lang); this.currentLang = localStorage.setItem("currentLa ...

What are the steps to customize the collapse and expand icons?

Having trouble changing the icon up and down when collapsing and expanding with the code below. <div class="attach-link"> <a href="javascript:void(0);" *ngIf="fileData.fileDataType.canAttach && !isFinancialEntity" (click) ...

Initiate the input change event manually

Struggling with creating a custom counter input component where the input value is controlled by custom increment/decrement buttons. Desired output: https://i.sstatic.net/oYl1g.png Content projection will be used to expose the input for form usage and a ...

What are the steps to utilize a personalized validation access form within a component?

I created a unique validator to verify if an email already exists in the database before saving a new user, however, it appears that the validator is not functioning properly. Here is my template: <form class="forms-sample" #f="ngForm" (ngSubmit)="onS ...

Exploring the possibilities of updating carousel items in Angular using Bootstrap

I'm working on a project where I have 4 images and a carousel that needs to navigate to the respective index when one of the images is clicked. The challenge is that the carousel is built with Bootstrap and jQuery, but the rest of the application is A ...

Discovering an array containing a specific value and transforming it to another array in Angular 8

I have an array called this.data which contains a list of platforms. Each platform has its own set of section lists, where a section list consists of values like sectionName, sectionid, and sectionVal. Now, my goal is to replace the old sectionList with a ...

Incorporating CodeMirror into Angular2 using TypeScript

I've been working on integrating a CodeMirror editor into an Angular2 project, but I'm encountering some issues with the instantiation of the editor. Here is my code snippet: editor.component.ts import {Component} from 'angular2/core' ...

What could be the possible reason for the token having a null value during login authentication in

As a beginner to Angular, I am facing an issue with my JWT login page implementation. Despite printing the token in the console and confirming its existence as a string, I am receiving a null (or undefined) value. This is the code snippet from my UserServi ...

Using the `require('ts-node/register')` method for programmatic implementation in TypeScript

ts-node recommends using require('ts-node/register'). This is also evident in the angular2-webpack-starter Protractor configuration. What exactly does require('ts-node/register') do? Does it modify require to compile TS files, allowing ...

Guide to implementing ion-toggle for notifications with Ionic 2 and Angular 2

Currently, I am using a toggle icon to set the notification as active or inactive. The response is obtained from a GET call. In the GET call, the notification value is either 0 or 1, but in my TypeScript file, I am using noteValue as boolean, which means w ...

After verifying the variable is an Array type, it is ideal to utilize the .forEach()

Within my generic functional component, I have the following code snippet: if(Array.isArray(entry[key as keyof T]) { entry[key as keyof T].forEach((item: T) => { ... }); } The variable key is a string that dynamically changes. However, when attempt ...