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

When the imagepath in an Angular application is not updated, it will revert to null

Below is the code snippet that I am currently working on: <div class="col-sm-4 pl-5"> <img attr.src="{{item?.imagePath}}" required height="200" width="200"> </div> In my TypeScript file (ts), I have the following function: editBlog ...

Can anyone provide a workaround for bypassing ts 2339 error in order to access class methods? Alternatively, is it feasible to define class methods outside of the class in typescript?

My plan is outlined below class A { constructor() { bind(this); } hello(){ this.method1(); // <-- I will get error at this line saying method one does not exist on typeOf A } } function bind(thisReference) { function method1() { ...

Issue with Next.js: Callback function not being executed upon form submission

Within my Next.js module, I have a form that is coded in the following manner: <form onSubmit = {() => { async() => await requestCertificate(id) .then(async resp => await resp.json()) .then(data => console.log(data)) .catch(err => console ...

"In Nextjs, it is not possible to utilize the alert function or assign variables directly to the window object

Are you attempting to quickly sanity test your application using the window object's alert function, only to encounter errors like "Error: alert is not defined"? import Image from "next/image"; alert('bruh'); export default function Home() ...

The value of 'Boolean' cannot be changed as it is a constant or a read-only property and cannot be assigned

I've been working on creating a TypeScript object to handle read/write permissions in my application, but I'm stuck on an issue with variable assignment that doesn't make sense to me. Any help or guidance would be greatly appreciated. expor ...

Animated drop-down menu in Angular 4

I recently came across this design on web.whatsapp.com https://i.stack.imgur.com/ZnhtR.png Are there any Angular packages available to achieve a dropdown menu with the same appearance? If not, how can I create it using CSS? ...

Refresh child route independently without relying on data from parent route

I am currently facing an issue with my component 'panel' that has two child routes: dashboard and holidays. Both of these child routes are supposed to receive data from the parent component service in their ngOnInit. While everything is working ...

The combination of Autodesk Forge Viewer and React with TypeScript provides a powerful platform for developing

I'm brand new to React and Typescript, and I have a very basic question. In the viewer documentation, extensions are defined as classes. Is it possible to transform that class into a typescript function? Does that even make sense? For example, take th ...

Transform leaflet marker plugin into Typescript format

I recently discovered a leaflet extension that conceals map markers if they fall outside the boundaries of the current view map. import L from 'leaflet'; L.Marker.MyMarker= L.Marker.extend({}).addInitHook(function (this: ILazyMarker) { this ...

Is it possible to pass additional arguments to setState other than prevState and props?

I'm currently facing an issue with my component that involves calling a function called addOption, which is defined on its parent component. This function takes a parameter 'option' from a form field and concatenates it with an array of opti ...

Retrieve a HashMap through an HTTP GET request using Angular 10

I am currently using the following versions: Angular CLI: 10.0.1 Node: 12.18.2 OS: win32 x64 Angular: 10.0.2 In my setup, I have a Java Spring Boot service that is functioning correctly and returns data as a HashMap. Map<String, List<String>&g ...

Is there a way to disable tslint warnings for npm linked packages?

Currently, I am in the process of developing a set of Angular/TypeScript components within an application that utilizes this package. To facilitate the sharing of these components, I have utilized npm link. However, upon building the project, I encountered ...

Employing the ng-token-auth function for logging in and submitting to an alternate URL

Currently, I am utilizing ng-token-auth along with angular/ionic to interact with a rails api. My focus right now is on the login page where I have implemented the following form: <form ng-submit="submitLogin(loginForm)" role="form" ng-init="loginForm ...

Why is it necessary to omit node_modules from webpack configuration?

Check out this webpack configuration file: module.exports = { mode: "development", entry: "./src/index.ts", output: { filename: "bundle.js" }, resolve: { extensions: [".ts"] }, module: { rules: [ { test: /\.ts/ ...

Encountering problem with npm ERR! peer @angular/common@"^12.0.0" while trying to install @ng-bootstrap/[email protected]

Encountering an issue during the deployment of my Angular application. I added the @ng-bootstrap/ng-bootstrap package, but there seems to be a dependency resolution problem causing the issue. 22-Dec-2022 07:03:47 npm ERR! Could not resolve dependency: 2 ...

Utilizing Array.every to refine a union of array types, narrowing down the options

I need to narrow down the type of a variable that is a union of different array types in order to run specific code for each type. I attempted to use Array.every along with a custom type guard, but encountered an error in TypeScript stating "This expressio ...

Is the RouterModule exclusively necessary for route declarations?

The Angular Material Documentation center's component-category-list imports the RouterModule, yet it does not define any routes or reexport the RouterModule. Is there a necessity for importing the RouterModule in this scenario? ...

Angular searchbar issue: Unable to assign parameter of type 'unknown' to parameter of type 'string'

I've been working on an Angular app to fetch data from an API successfully. However, I'm currently facing a challenge while implementing a search function in my component.ts file. Here is the entire service code: import { Injectable } from &apos ...

Resolving compatibility issues between FullCalendar and Angular 8

Encountering an issue in the console while using Angular 8: The error message reads: Module '../../../../../../../../node_modules/@fullcalendar/angular/fullcalendar-angular' has no exported member 'CalendarOptions'. Past solutions inv ...

Tips for converting numerical values in a JSON object to strings within a TypeScript interface

{ "id": 13, "name": "horst", } in order to interface A { id: string; name: string; } When converting JSON data of type A to an object, I expected the conversion of id from number to string to happen automatically. However, it doesn' ...