What is the best way to implement a counter with setInterval in Angular?

As a beginner in Angular, I am trying to utilize the setInterval function to count numbers, but I am facing difficulties in achieving success. Can someone provide assistance with this issue? (Apologies for any grammar mistakes in my English.) Thank you in advance.

Below is my success-facts.component.ts

import {Component} from '@angular/core';

@Component({
  selector: 'app-success-facts',
  templateUrl: './success-facts.component.html',
  styleUrls: ['./success-facts.component.css']
})

export class SuccessFactsComponent {
  startValue: number = 0;
  countNumber: any = setInterval(() => {});
  projectCountStop: any = setInterval( () => {
    this.countNumber++;
    if(this.countNumber === 20 ) {
      clearInterval(this.projectCountStop)
    }
  }, 10 )

  public successCounterData: any[] = [
    {
      id: 0,
      countNumber: setInterval(() => {
        this.startValue++;
        if(this.startValue == 2) { 
          clearInterval() // I don't know what should I use for parameter here, I should use "countNumber" but I can't use
        }
      },10),
      text: 'Project Complete',
      isRate: false,

    },
    {
      id: 1,
      countNumber: 5000,
      text: 'Happy Clients',
      isRate: false,
    },
    {
      id: 2,
      countNumber: 25,
      text: 'Years Experience',
      isRate: false
    },
    {
      id: 3,
      countNumber: 90,
      text: 'Success Rate',
      isRate: true
    },
    {
      id: 4,
      countNumber: 35,
      text: 'Expert Advisors',
      isRate: false
    }
  ]
}

Below is my success-facts.component.html

<div *ngFor="let count of successCounterData" class="count-column">
  <div class="inner-box count-box">
    <div class="count-outer">
      <span *ngIf="count.isRate; else elseBlock" class="count-text">{{ count.countNumber }}%</span>
      <ng-template #elseBlock>{{startValue}}</ng-template>
    </div>
    <h4 class="counter-title">{{ count.text }}</h4>
  </div>
</div>

While attempting to use the setInterval function along with clearInterval, I am unsure of how to implement it within an array, particularly the parameter required for the clearInterval function.

{
  id: 0,
  countNumber: setInterval(() => {
    this.startValue++;
    if(this.startValue == 2) { 
      clearInterval()
    }
  },10),
  text: 'Project Complete',
  isRate: false,
},

My goal is to increment numbers without the need for a button or click event.

Answer №1

I encountered and resolved a problem using the OnInit method. For anyone facing a similar issue, here is the solution:

success-facts.component.html

<div *ngFor="let count of successCounterData" class="count-column">
  <div class="inner-box count-box">
    <div class="count-outer">
      <span *ngIf="count.isRate; else elseBlock" class="count-text">{{ count.count }}%</span>
      <ng-template #elseBlock>
        {{count.count}}
      </ng-template>
    </div>
    <h4 class="counter-title">{{ count.text }}</h4>
  </div>
</div>

success-facts.component.ts

import {Component, OnInit} from '@angular/core';


@Component({
  selector: 'app-success-facts',
  templateUrl: './success-facts.component.html',
  styleUrls: ['./success-facts.component.css']
})

export class SuccessFactsComponent implements OnInit {
  countNum: number = 0;
  targetCount: number = 100;
  interval: any;


  public successCounterData: any[] = [
    {
      id: 0,
      countNumber: 20000,
      count: 0,
      text: 'Project Complete',
      isRate: false,

    },
    {
      id: 1,
      countNumber: 5000,
      count: 0,
      text: 'Happy Clients',
      isRate: false,
    },
    {
      id: 2,
      countNumber: 25,
      count: 0,
      text: 'Years Experience',
      isRate: false
    },
    {
      id: 3,
      countNumber: 90,
      count: 0,
      text: 'Success Rate',
      isRate: true
    },
    {
      id: 4,
      countNumber: 35,
      count: 0,
      text: 'Expert Advisors',
      isRate: false
    }
  ]

  ngOnInit(): void {
    this.startCounting();
  }

  startCounting() {
    const interval = setInterval(() => {
      let allItemsFinished = true;
      this.successCounterData.forEach((item) => {
        if (item.count < item.countNumber) {
          item.count++;
          allItemsFinished = false;
        }
      });
      if (allItemsFinished) {
        clearInterval(interval);
      }
    }, 1);
  }
}

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

Extracting data from HTML elements using ngModel within Typescript

I have an issue with a possible duplicate question. I currently have an input box where the value is being set using ngModel. Now I need to fetch that value and store it in typescript. Can anyone assist me on how to achieve this? Below is the HTML code: ...

Experiencing migraines while integrating Firebase 9, Redux Toolkit, and Typescript in a React project. Encountering a peculiar issue where 'dispatch' is unexpectedly identified as type 'never'?

I am currently in the process of upgrading an old project to newer technologies, specifically focusing on Typescript, redux-toolkit, and Firebase v9 for modularity. While I have limited experience with Typescript and none with redux-toolkit, I have been us ...

Sharing information between different components in React can be done using props, context, or a

When attempting to edit by clicking, the parent information is taken instead of creating a new VI. I was able to achieve this with angular dialog but I am unsure how to do it with components. This is done using dialog: <div class="dropdown-menu-item" ...

Exploring two main pages, each with tabs displaying two negative behaviors

I developed an app with an ion-footer at the bottom of each root page : <ion-footer> <ipa-footer-buttons></ipa-footer-buttons> </ion-footer> The <ipa-footer-button> component is structured as follows: html: <ion-toolb ...

PHP: Transform an array containing a path attribute into a hierarchical tree format

Imagine we have an array like the one shown below: $myArray = array( array( "id" => 1, "name" => "Europe", "path" => "/" ), array( "id" => 2, "name" => "Germany", "path" => ...

Having trouble getting the Angular Route to work, any tips on how to fix it?

I am currently learning Angular and have encountered a small issue. When I place the Component in my app.component.html as shown below, it functions correctly: <body> <div class="container"> <app-search-books></app-search-books ...

Managing the onChange event for a MaterialUI dropdown component

I'm encountering an issue with validating the MaterialUI TextField component (Country list) wrapped with Autocomplete. I am trying to use the onChange event to enable the Submit button when the country field is filled in. However, the problem arises w ...

TypeORM does not have the capability to effectively remove a row when there is a ManyToOne or

I'm currently grappling with a problem that has me stumped. I've spent countless hours trying to find a solution, but to no avail. I'm using MS-SQL on Azure. The structure of my entities is as follows: Customer and Visits: OneToMany (Prima ...

The declaration file for the datepicker module could not be located, even though the necessary types have been installed

I'm encountering an issue during production build on my Next.js project. The error message reads: Could not find a declaration file for module 'react-datepicker'. '../node_modules/react-datepicker/dist/index.js' implicitly has an ...

Item removed from the cache despite deletion error

Currently, I am utilizing Angular 8 along with @ngrx/data for handling my entities. An issue arises when a delete operation fails (resulting in a server response of 500), as the entity is being removed from the ngrx client-side cache even though it was not ...

Records of docker-related errors detected in the logs

I am looking to release the Angular application with GitLab CI/CD pipeline on Azure. I have set up the GitLab pipeline as shown below: Upon deployment, I encountered errors in the logs which are displayed below: Seeking assistance to resolve this issue ...

Learn how to utilize the "is" status in Postma within your code, even when this particular status is not included in the response

Service.ts Upon invoking this function, I receive a JSON response similar to the following: public signupuser(user: Users): Observable<boolean> { let headers = new Headers(); headers.append('Content-Type', 'application/json&a ...

"Encountering a 400 bad request error when making a Graphql POST

Seeking assistance with my graphql code. I have included the service and component files below. I am currently new to graphql and not utilizing the apollo client; instead, I am attaching a query on top of the HTTP POST call to send requests to the graphql ...

Tips for integrating yarn add/npm install with monorepositories

I am attempting to retrieve a node package from a private monorepo on GitHub, structured similarly to this: monorepoProject --- subProjectA --- subProjectB Both subProjectA and subProjectB are TypeScript projects, following the layout depicted below: ...

The service functions are being called two times consecutively

I am utilizing an authentication component @Component({ selector: "oe-authentication-view", templateUrl: "./authentication-view.component.html" }) export class AuthenticationViewComponent implements OnInit { authorizationFormGroup: FormGroup; ...

HTML5 Drag and Drop: How to Stop Drag and Drop Actions from Occurring Between a Browser and Browser Windows

Is it possible to restrict HTML5 Drag & Drop functionality between different browsers or windows? I am currently working on an Angular2 app that utilizes native HTML5 Drag and Drop feature. Is there a way to prevent users from dragging items out of th ...

Styling Form validation with Ant Design

Can a className prop be included in the Form.Item validation? <Form.Item name="username" rules={[ { required: true, message: '...' }, className="customValidation" //<- attempting to add a className but it is not fu ...

Issue with Adding Class to Angular2 Material Tooltips

Here is the code from my component.html file: <tr> <td> <span matTooltipClass="primary-tooltip" matTooltipPosition="above" matTooltipHideDelay="100000" matTooltip="{{cert.awsCertId}}"><p style="overflow:hidden;text-overflow: ellip ...

Angular Compilation Errors Caused by Component Inheritance

My parent Component is structured like this: import { Component} from '@angular/core'; @Component({ selector: 'app-main-parent', template: '', }) export class ParentComponent { constructor(protected service) { ...

Angular Universal functioning fine on local host, yet encountering issues on Nginx Server

I recently developed a project with Angular Universal. After building the project, it generated files such as browser, server, server.js, and prerender.js. I am curious to learn how I can run this project on an nginx server. Currently, I create a build o ...