Updating the variable does not cause the h2 interpolation to be refreshed

There seems to be an issue with the h2 interpolation not updating when the variable changes. My goal is to make it appear as though the word is being typed out by adding letters to the displayedWord variable. TS

  displayedWord = ''
  words = ['Innovation', 'Inspiration']


  changeWord = (words) => {

    const wordArray = this.words[0].split('')
    const lettersToDisplay = []

    for (let i = 0; i < wordArray.length; i++) {
      setTimeout(function () {
        const letter = wordArray[i];
        lettersToDisplay.push(letter)
        this.displayedWord = lettersToDisplay.join('');
        console.log(this.displayedWord);
      }, 1000 * i);
    }
  }


  ngOnInit(): void {
    this.changeWord(this.words);
  }

HTML

        <h2 class="about__title">Discover the magic of {{displayedWord}}_

Answer №1

It's crucial to update:

setTimeout(function() { ... } )

To:

setTimeout(() => {...})

So that this correctly references the component instance.

Check out the details here.

Explains how:

Does not have its own bindings to this.

contrasted with function expression

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

Encountering issues in d3.js following the transition to Angular 8

After upgrading my Angular 4 app to Angular 8, I encountered an issue where the application works fine in development build but breaks in production build. Upon loading the application, the following error is displayed. Uncaught TypeError: Cannot read p ...

Ionic: Dismiss the splash screen only upon reaching the last view in the stack

In my Ionic app, I am faced with the following use case involving the implementation of the splashsscreen plugin : 1. When the user is not logged in: Show SplashScreen > LoginPage pushed to stack > Hide SplashScreen on the login page 2. If the u ...

Retrieving display format or formatted value from an object with Moment.js

I am currently working on a project using Angular and Material2. Within this project, I have created a moment object in the following way: myDate = moment.utc(new Date()).format("YYYY-MM-DD HH:mm:ss"); This object is then passed as an argument to ano ...

What is the process for causing an Observable that already exists to emit specialized data?

Let's say I have an Observable that was created in the following way: let observable = of(mockData).pipe(delay(5000)); Is there a method to emit a new value to the observers who are currently subscribed to this observable at a later time? I came acr ...

The process of attaching a click event to a mat-step-header

How can I activate a function when a user clicks on mat-step-header? I attempted to include (click) on <ng-template matStepLabel><span (click)="triggerClick()">step 1</span></ng-template> but the function is only triggered by click ...

Jasmine: A guide to mocking rxjs webSocket

Here is my chat service implementation: import {webSocket, WebSocketSubject} from 'rxjs/webSocket'; import {delayWhen, retryWhen, take} from 'rxjs/operators; import {timer} from 'rxjs; ... export class ChatConnectionService { priva ...

An unexpected issue occurred while attempting to create a new Angular app using the command ng

Currently in the process of deploying my angular application and utilizing Infragistics. Following their Documentation, I used npm install Infragistics for installation. However, when I run ng new --collection="@igniteui/angular-schematics" I e ...

Exploring Function Type in TypeScript: Utilizing both fat arrow and object literal type

Currently delving into the world of Typescript, I came across two methods for defining function types: using a fat arrow or an object literal. Here's an example: let myAdd1: (x: number, y: number) => number = function(x: number, y: number): n ...

Tips for adjusting column sizes in ag-grid

I'm a beginner with ag-grid and need some help. In the screenshot provided, I have 4 columns initially. However, once I remove column 3 (test3), there is empty space on the right indicating that a column is missing. How can I make sure that when a col ...

Creating spec.ts files for components by hand: A guide

Currently, I am facing an issue where the automatic generation of spec.ts files has been disabled by the developers when they created the components. To address this, I manually created the spec.ts files by copying over an existing one into each component, ...

Is it possible for React props to include bespoke classes?

In our code, we have a TypeScript class that handles a variety of parameters including type, default/min/max values, and descriptions. This class is utilized in multiple parts of our application. As we switch to using React for our GUI development, one of ...

Displaying JSON data using FormControls in Angular 5

Upon receiving Json values from the server, I am encountering an issue while binding them to respective textboxes. The problem arises as the value in the textbox appears as [object object] <h1>{{title}}</h1> <h3>Catalog</h3> ...

Collection of personalized forms where the parent is a FormGroup

One scenario I'm working on involves creating multiple custom formgroup classes that have FormGroup as their parent class, structured like this: export class CustomFormGroup1 extends FormGroup { //custom properties for this FormGroup const ...

Is there a way to implement an extra placeholder attribute with Angular4?

Currently, in a project where I am utilizing Angular Material, there is a form integrated with an autocomplete component. The functionality works as expected but I am interested in implementing placeholder text once the user focuses on the input element. ...

Is it considered overboard to import an entire shared module in Angular just to use one specific feature from it?

Consider a scenario where I have a UtilityModule that imports various utilities such as services, pipes, and more. Now, in FeatureModuleX, I only need to utilize one specific pipe from the UtilityModule. By importing the entire UtilityModule into FeatureM ...

Is there a proper way to supply createContext with a default value object that includes functions?

As I was creating my context, I set an initial state and passed the necessary functions for useContext. Although this method is functional, I'm concerned it may present challenges in larger projects. Does anyone have suggestions for a more efficient a ...

A custom function that changes the state of a nested object using a specified variable as the key argument

My goal is to update the state of an object using a function called updateDatas. This function takes the arguments key, possibly subKey, and value. interface Datas { code: number; item1: Item; } interface Item { id: number; name: string; } const ...

Unable to access the FormControl instance directly. It is not possible to read the property 'invalid' of an undefined value

Accessing in Angular docs is not the same as before, you must first grab the FormGroup instance and then find the FormControl instance within it. I wonder why? This example works: <form [formGroup]="myForm" (ngSubmit)="onSubmit()"> <div class=" ...

CORS policy has blocked access to XMLHttpRequest from the origin because the requested resource does not have the 'Access-Control-Allow-Origin' header

I recently built an API project using MVC Core. Everything seemed to be working fine when testing the GET and POST methods with Postman. However, I encountered a CORS error when trying to call these APIs from my Angular App: Access to XMLHttpRequest fro ...

What is the best approach in Typescript to ensure type understanding when importing using require()?

Currently, I am working with TypeScript within IntelliJ. Let's say I have the following code: const functions = require('firebase-functions'); Then I proceed to use it in this manner: exports.doSomething = functions.https.onCall((data, c ...