Implementing a delay for triggering an event in Angular based on certain conditions

I'm trying to create a div that triggers a click event. When the user clicks on the "click here" label, I want an alert to appear based on two conditions: first, if getListData is true, and second, only if the label is clicked after 5 seconds of getListData being true. However, my current code isn't working as expected. Here's the snippet below:

home.component.html

<div (click)="clickhere()">Click here</div>

home.component.ts

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router'; 
@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
  getListData: boolean = false;
  constructor(private router: Router) { }

  ngOnInit() {

  }
  clickhere(){
      this.getListData = true;
      console.log(this.getListData);
      setTimeout(function(){
      if(this.getListData == true){
         alert('true'); 
      }
      }, 3000);
  }

}

Answer №1

When working with the setTimeout function, keep in mind that 'this' context is not directly accessible. One way to work around this is by using an arrow function to define the callback and maintain the correct context.

function clickhere(){ this.getListData = true; console.log(this.getListData); setTimeout(()=>{
if(this.getListData){ alert('true'); } }, 3000);
}

If you need more information on this topic, check out:

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

Enhancing the Angular Currency Pipe to display zeros after the decimal point

Using Angular has strict requirements for displaying full numbers received from the backend. In some cases, like with "123.450" and "123.45," the amount may be the same but clients prefer to see the complete number. <td>{{ material.customerPrice | ...

What are the key distinctions between an arrow function, a class, and a traditional function?

Is there a way to distinguish between the following three elements in ES6 using its reference? let x = i => i+1; class y { constructor(i) { this._i=i+1; } get i(){ return this._i;} } function z(i) { return i+1; } For example: test(x) //=> ' ...

The ion-slide-box does not function properly the first time the HTML page is loaded

Upon loading the page, my ion-slide-box does not function correctly. However, if I refresh the page, it works as expected. I have tried referring to some links but have been unable to resolve this issue on my own. Any assistance would be greatly appreciate ...

How to dynamically style table cells in Angular 11 using ng-class and *ngFor

Currently, I am working on populating a table by looping through an array using *ngFor directive. Although the table is getting populated successfully, I am looking to dynamically change the background color of a cell based on the value it contains. For i ...

What is the process for streaming an mp3 file using express?

I have been utilizing the gTTS module to convert text into a .mp3 file and temporarily save it. However, I am encountering an issue when attempting to stream the file, as the arraybuffer in the response object returned by the endpoint appears to be empty. ...

Is there a way to modify the text of image URLs using JavaScript?

My method of replacing a specific word in text works like this: document.body.innerHTML = document.body.innerHTML.replace(/katt/g, "smurf"); However, when I try to replace an image URL in HTML using the same line of code, it doesn't seem to work. H ...

Efficient method to access two arrays simultaneously and combine them into an associative array in JavaScript

When using Ajax to return a table, you have the option of separating column names and row values. Here are two ways to do it: let columns = ["col1", "col2", "col3"]; let rows = [ ["row 1 col 1", "row 1 col 2", "row 1 col 3"] , ["row 2 col 1", "r ...

Node.js has the ability to establish internal connections, however it cannot establish connections

I'm having an issue connecting to a JavaScript file on my local server. I'd like to input the external IP address and port in order for it to run externally. This functionality currently works when accessed locally. Below is the code from my serv ...

Ways to update the angular content following a switch in the current bootstrap tab?

My component displays multiple tabs, with only one active depending on the business logic. Here is a snippet of the code: <ul class="nav nav-tabs"> <li *ngIf="activateTab1" class="active"><a data-toggle="tab" href="#tab1"> < ...

Issues arise when attempting to utilize Node.js Socket.io on localhost, as the calls are ineffective in performing logging, emitting, generating errors, or executing any other actions. It has been noted that

I am in the process of developing a real-time socket.io application using Angular and Node, following the instructions provided here. I have set up the server and client connection, but unfortunately, the connection is not being established. Server Code: ...

Troubleshooting a Typescript application by incorporating console input during runtime

I am currently delving into learning typescript and I am in need of assistance in setting up debugger support in VS code. I have a simple TS app that functions as a standalone application, printing "Hello World" to the console when data is entered. How can ...

Increase the date by one day in the minimum date field using the date picker

I've been struggling with adding one day to the minDate in my code. Despite trying multiple solutions from Stackoverflow, none of them have worked successfully. Here is the code I currently have: $('#cal_mulamhn').datepicker({ minDate ...

Error: Unable to execute fields.map function while generating a dynamic sitemap using next-sitemap module

I'm in the process of creating a dynamic sitemap for my website and here's the code I'm using: import { GetServerSideProps } from 'next'; import { getServerSideSitemap, ISitemapField } from 'next-sitemap'; import { makeSl ...

Issues with Jquery content sliders

I am really struggling with this piece of code and I just can't seem to figure out what's causing the issue. If anyone has any insight on how I can make it display a slide for 3 seconds, fade out, show a new slide, and then loop back to the first ...

Error message: "The use of Vue 3 refs in the render function is

I am facing an issue with my Vue component wherein the root element is set as ref="divRef". Strangely, when I try to access divRef.value inside the onMounted function, it returns undefined. Any assistance on this matter would be greatly appreci ...

Using Node.js to implement pagination with the POKEapi through a loop

Recently, I've been experimenting with the POKEapi to display information on 150 different pokemons. This is my first attempt at creating a node.js app as I'm just starting to learn javascript. The challenge I'm facing now is implementing ...

Imagine a complex JSON structure with multiple levels of nesting

Take a look at this JSON data : { department_1 : [{ id : 1, name = Joe Smith, email : <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="660c150b0f120e2613150048030213">[email protected]</a>}, ...., { id : 500, name ...

What is the most efficient method for appending /.json to the conclusion of express routes?

I am currently transitioning a DJANGO API to Node.js and have been tasked with ensuring that routes support the .json extension at the end. For instance, sending a GET request to /users/:id/.json should return a JSON object representing the user. The cha ...

What are the steps for integrating a CMS with my unique website design?

Currently, I am in the process of creating a unique website for a client using my own combination of html, css, and JavaScript. There is also a possibility that I may incorporate vueJS into the design. The client has expressed a desire to have the ability ...

Updating values using events within a v-for loop in a Vue template: A step-by-step guide

Just starting out with Vue and Laravel! Currently, I am retrieving data from an API Resource in Laravel. The API consists of 2 fields: Goal Value Here is the code snippet: <template> <div class="container"> <h1> Progress ...