Experience feelings of bewilderment when encountering TypeScript and Angular as you navigate through the

Exploring Angular and TypeScript for an Ionic project, I am working on a simple functionality. A button click changes the text displayed, followed by another change after a short delay.

I'm facing confusion around why "this.text" does not work as expected, depending on how the timeout function is implemented.

The following code snippet shows where the issue arises:

export class HomePage {
  constructor() { }

  text = "Default";

  onChangeText() {
    this.text = "Changed!";
    setTimeout(
      this.onBackToDefault
      , 2000);
  }

  onBackToDefault() {
    this.text = "Default";
  }
}

However, the problem is resolved with the revised code below:

export class HomePage {
  constructor() { }

  text = "Default";

  onChangeText() {
    this.text = "Changed!";
    setTimeout(() => {
      this.onBackToDefault();
    }
      , 2000);
  }

  onBackToDefault() {
    this.text = "Default";
  }
}

Answer №1

The reason for this behavior is that this inside a function refers to the function itself, while in an arrow function it refers to the outer scope.

In the first scenario, you are passing the entire function as an argument, whereas in the second scenario, you are using an arrow function.

To illustrate this point further, consider the following alternative version of the first example:

handleTextChange() {
  this.text = "Modified!";
  setTimeout(function () {
    this.revertToDefault();
//       <------ In this case, 'this' is scoped to the anonymous function
  }, 2000);
}

Answer №2

setTimeout(
  this.executeFunction
, 2000);

When using the setTimeout method in this context, it only recognizes elements declared inside it. This means that any elements referenced with this. will be undefined.

To workaround this issue, you should use parentheses when calling setTimeout in order to utilize external parameters:

setTimeout(() => {    
// perform desired actions    
}, 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

What is causing the malfunction in this overloaded function signature?

Encountering an issue when attempting to declare an overloading function type with a full type signature in TypeScript. For example: // Full type signatures for functions type CreateElement = { (tag : 'a') : HTMLAnchorElement, (tag ...

What is the process for installing Ionic with composer?

I attempted to set up the npm bridge by executing the following: $ composer require eloquent/composer-npm-bridge:^3 In the hopes of being able to install packages for Ionic using npm. Unfortunately, my plan seems to be failing as I keep encountering thi ...

Guide to utilizing @types/node in a Node.js application

Currently, I am using VSCode on Ubuntu 16.04 for my project. The node project was set up with the following commands: npm init tsc --init Within this project, a new file named index.ts has been created. The intention is to utilize fs and readline to read ...

Angular 6 - Outdated Functions

I'm having trouble updating the request options as they are now deprecated. I can't seem to locate the alternative option for this. Can anyone offer some assistance? import { Injectable } from '@angular/core'; import { HttpClient } fr ...

What is the best way to retrieve a soft deleted entity from typeorm in a postgreSQL database?

Can anyone help me figure out how to retrieve soft deleted documents from a PostgreSQL database using TypeORM's find, findOne, or query builder get/getMany methods? I keep getting undefined as the result. Is there a way to access these deleted values? ...

Tips for waiting for an observable loop

When using my application, the process involves uploading a series of images in order to retrieve the file IDs from the system. Once these IDs are obtained, the object can then be uploaded. async uploadFiles(token: string):Promise<number[]> { let ...

Issue encountered while defining a component in Angular 16

Currently, I am in the process of learning Angular by following the tutorial provided on Angular.io. As part of this journey, I have declared a home component within my Angular application using the given code: ng generate component home --standalone --in ...

Having trouble viewing objects' content in the JavaScript console in Visual Studio 2015?

In the past, I was able to see all the content of my JavaScript objects like this: However, for some reason now, the content is not being displayed at all: I am using Visual Studio 2015 Community with Cordova and Ripple emulator. I have tried creating a ...

While working with Ngrx/effects, an error with code TS2345 occurred. The error message stated that the argument is of type 'Product[]', which cannot be assigned to a parameter of type

When I compile my code, I encounter the following issue (despite not finding any errors in the browser console and the application functioning properly). An error occurs in src/app/services/product.service.ts(15,9): The type 'Observable<Product> ...

"Zone has been successfully loaded" - incorporating angular universal ssr

I am currently working on an Angular project and I am looking to implement server-side rendering. To achieve this, I decided to use Angular Universal. The browser module of my project was successfully built, but I encountered the following issue during the ...

Angular Form customizable field

I'm trying to figure out how to create an angular form with a dynamic step. Currently, my form in TypeScript looks like this: this.registerForm = new FormGroup({ role: new FormControl('', [ Validators.required, ]), firstName: ...

I encounter an issue while attempting to add Firebase to my Angular project

I am facing an issue while trying to install Firebase in my Angular project. The command I used for installation is: npm install firebase @angular/fire --save However, when running this command, I encountered the following error: npm ERR! Unexpected end ...

Initial state was not properly set for the reducer in TypeScript

Encountered an error while setting up the reuder: /Users/Lxinyang/Desktop/angular/breakdown/ui/app/src/reducers/filters.spec.ts (12,9): error TS2345: Argument of type '{}' is not assignable to parameter of type '{ selectionState: { source: ...

Receive characteristics in component specification

Is there a way to pass the native attributes of an img element to a custom image component without explicitly defining each one, like alt, and have them all be applied to the img tag? Here is an example of what I mean: @Component({ selector: 'image ...

Converting the information retrieved from Firebase into a different format

My Project: In my Angular SPA, I am trying to retrieve data from Firebase and display specific values on the screen. Approach Taken: The data returned from Firebase looks like this: Returned Data from Firebase Error Encountered: In order to display the ...

Change TypeScript React calculator button to a different type

I am currently troubleshooting my TypeScript conversion for this calculator application. I defined a type called ButtonProps, but I am uncertain about setting the handleClick or children to anything other than 'any'. Furthermore, ...

Authenticating Keycloak Object in Angular 2 - Verify the Authenticated Status

Incorporating the Keycloak authentication service into my Angular 2 project has been a learning experience. I have set up a service to handle logging in and out functionalities. Successfully authenticating a user and logging them out was relatively smooth ...

Verifying a data field in a document in Cloud Firestore for a particular value

Is there a way to validate the existence of a username in my Users Collection before allowing user registration? The usernames are stored on user documents in Firestore. https://i.stack.imgur.com/WARAs.png I'm looking for a snippet or solution that ...

Retrieve upcoming route details within canDeactivate guard in the updated Angular2 router

Is there a way to retrieve the upcoming route information within the "canDeactivate" guard of Angular 2's new router? ...

The JSX component cannot be named 'Stack.Navigator' or used as such

Encountering a type issue with react navigation using Stack.Navigation or Stack.Group from createNativeStackNavigator The error message indicates that the types do not match with JSX.element. Specifically, it states: Type '{}' is not assignable ...