Issue with accessing global variable in nested function using "this" in Angular 2

Having recently delved into Angular 2, I find myself facing a challenge with accessing the "task_title" within the startTimer() function. The console.log() returns undefined and I suspect it's due to "this" referring to the function itself instead of the value of "task_title".

Is there a way in Typescript to access a global variable within a nested function?

export class DashboardComponent {

    task_title: string;

    myTimer = setTimeout(this.startTimer, 2000);

    updateTask(event: any){
        clearTimeout(this.myTimer);
        this.task_title = event.target.value;
        this.myTimer = setTimeout(this.startTimer, 2000);
    }

    startTimer() {
        console.log(this.task_title);
        this.myTimer = setTimeout(this.startTimer, 2000);
    };
}

Outcome: Undefined.

Answer №1

To maintain the scope of this, consider using arrow functions or the .bind(this) method.

myTimer = setTimeout(this.beginTimer.bind(this), 2000);
myTimer = setTimeout(() => this.beginTimer(), 2000);

Answer №2

Make sure to use the reference variable 'self' in your code like var self=this

export class DashboardComponent {

var self=this;


task_title: string;

myTimer = setTimeout(self.startTimer, 2000);

updateTask(event: any){
    clearTimeout(self.myTimer);
    self.task_title = event.target.value;
    self.myTimer = setTimeout(self.startTimer, 2000);
}

startTimer() {
    console.log(self.task_title);
    self.myTimer = setTimeout(self.startTimer, 2000);
};
}

Answer №3

Employing call or apply method

myClock = setTimeout(this.activateClock.call(this), 2000);
myClock = setTimeout(this.activateClock.apply(this), 2000);

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

When array.push is used inside another array, it results in an undefined value

While working on defining an array within the Fire array in my code, I encountered a problem. When I tried to use console.log() to display the length of the array inside the Fire[] array for debugging, I received an error indicating that the array was und ...

Guide to assigning unique identifiers to all elements within an array using JavaScript

I have an array of objects with numeric keys that correspond to specific data values. I am attempting to restructure this object in a way that includes an 'id' field for each entry. Here is the original object: [ { "1": "data1", "5": "d ...

The MaterialUI Datagrid is throwing an error message for an Invalid Hook Call

Having a strange issue with my simple component. I've imported DataGrid from MaterialUI, defined variables for columns and rows, and rendered the DataGrid in a functional component. However, I'm getting an "invalid hook call" error. Most solution ...

Having trouble retrieving the selected dropdown value in Angular 5 using <p-dropdown> from PrimeNG due to issues with the ngOnInit function. Need some assistance with

My values are currently being populated in the ngOnInit() method, so the event is not available there. I need to retrieve the previously selected value even after refreshing the page. <p-dropdown [options]="Options" [(ngModel)]="Id" (onChange)="onChang ...

Newly inserted table columns aren't compatible with event listeners

My HTML table structure varies depending on the content of the uploaded CSV file. I have integrated a plugin called Dragtable to make the table columns draggable. Additionally, I have implemented methods to add rows and columns. Here is an example of the a ...

"I seem to be unable to retrieve all the data points for the X and Y axes on my nvd3 graph. Could there be some options that I am

https://i.sstatic.net/ITbJm.png I am encountering difficulty in obtaining all the X and Y intersection points on the axis as shown in the graph image. Additionally, I would like to emphasize the intersection points with a dark circle. Any assistance in re ...

Having trouble with a Javascript function not executing upon form submission

I decided to give this tutorial a try: and I'm experimenting with it on my sandbox site here: But, when I click the submit button on the form to add a problem, nothing happens. There isn't even any output in the Chrome JavaScript console. I tr ...

Display a dynamic selection of images from a folder in ASP.NET based on the option chosen in a dropdown list

Is there a way to dynamically load multiple images from a folder in ASP.Net based on the selected option in a dropdown list? I'm trying to implement this in Visual Studio and need some help. Below is the code I've been working with, but I'm ...

An issue has occurred due to an illegal state while attempting to utilize two modules within a single

When a user logs into my system, they are redirected to the profile page /profile/profile.component.ts after entering correct login credentials. Now, I want to implement an additional module for protected pages/components like the profile page and redirect ...

Checking with Protractor to see if the modal is displayed

I am currently working on a Protractor test to check if a bootstrap modal window that confirms the deletion of a record is visible at this time. The record that needs to be deleted is displayed in an angular ng-repeat, so I have to trigger the delete butt ...

Tips for adjusting the width of columns automatically in exceljs

One of my challenges is to automatically adjust column width using exceljs. I want the Excel sheet to be dynamic, saving only the columns specified by the user in the request. Here is the code snippet that accomplishes this: workSheet.getRow(1).values = dt ...

Solving issues with malfunctioning Angular Materials

I'm facing an issue with using angular materials in my angular application. No matter what I try, they just don't seem to work. After researching the problem online, I came across many similar cases where the solution was to "import the ...

Customize each Picker.Item element in React Native with unique styles

How can I style individual Picker.Items beyond just changing the text color? Additionally, what other props can be used for a Picker.Item? I am aware of "key", "value", "label", and "color". Are there any additional props available? I want to customize o ...

How can I adjust the padding and width attributes of the mat-menu in Angular 5

Today, I am struggling with a piece of code. Whenever I click on the Details button, it is supposed to open a mat-menu. However, for some reason, I cannot seem to adjust the padding or width of the menu: <div id="box-upload" [hidden]="hiddenBoxUpload" ...

"Endless Cycle Dilemma" Enigma

Upon executing the function below, I encountered the following error: "Error: Possible infinite loop." The issue appears to stem from the use of "0" in the splice method, as changing it to any other number (1-9) eliminates the error. I'm uncertain ...

What is the best way to utilize a dynamically allocated array across various functions?

#include <stdio.h> #include <stdlib.h> int readingNumbersFromFile(const char*file_name){ FILE*file=fopen(file_name,"r"); if(file==NULL){ return -5; } int count=-8; int number; while(fscanf(file,"% ...

Enhancing the Performance of jQuery Scripts

My jQuery function called textfill is utilized on numerous div elements. Essentially, it resizes the text inside each div to perfectly fit the container so that longer texts are made smaller than shorter ones while maintaining the maximum font size without ...

Identical names found in typescript within a react project

Having an issue with my react project where I am seeing a lot of duplication errors in almost all files located in this directory: C:\Users[user]\AppData\Local\Microsoft\TypeScript\4.3\node_modules@types\ I suspect ...

Tips on keeping text within a Bootstrap 4 card using a horizontal scroll card flip feature

Currently, I am working on developing a horizontal scroll feature that allows for cards to flip. One issue I am encountering is how to keep the text within the cards while still enabling scrolling functionality. The 'white-space: nowrap;' propert ...

When the component I created for dark mode is clicked, the colors in react-tsparticles change dynamically

I am looking to modify the theme of the react-tsparticle component function Particle() { const particlesInit = (main) => {}; const particlesLoaded = (container) => { <DarkMode />; container.loadTheme("dark&q ...